Jhipster: redirect to login page - spring-boot

How to redirect to login page if a specific exception is raised in JHipster?

There is a class in JHipster ExceptionTranslator which is used to handle the raised exceptions.
You can handle whatever exception you want to handle in the desired way.
#ExceptionHandler(MyException.class)
#ResponseStatus(HttpStatus.UNAUTHORIZED)
#ResponseBody
public String processJwtException(MyException ex) {
log.error("MyException occured : ", ex);
return "redirect:login_url";
}

Related

Does spring boot automatically take care of error handling in the context of JpaRepository methods?

When using Spring Boot, I am unsure if error handling is already being taken care of by the Spring Framework, or if I have to implement it. For example, consider a controller method, which handles a DELETE request:
#DeleteMapping("/{studentId}")
public ResponseEntity<Long> deleteProfilePicture(#PathVariable Long studentId) {
return ResponseEntity.ok(profilePictureService.deleteprofilePictureByStudentId(studentId));
}
Is this fine, or should I instead wrap it inside a try-catch block:
#DeleteMapping("/{studentId}")
public ResponseEntity<Long> deleteProfilePicture(#PathVariable Long studentId) throws Exception {
try {
profilePictureService.deleteProfilePictureByStudentId(studentId));
} catch (DataAccessException e) {
throw new Exception("cannot delete profile picture of student: " + studentId);
}
}
Also: If I let my method deleteProfilePicture throw this Exception, who is handling the Exception? This must somehow be taken care of by Spring Boot, since it is possible to implement it without yielding any errors. Anyhow, what is the correct way of error handling in this scenario?
Spring Boot will turn the exception into an error response to the caller of the REST API. This does not mean that you shouldn't implement your own error handling logic, which you definitely should. As an example, you could use #ControllerAdvice to have a global exception handling for your application. Something along the following lines:
#ControllerAdvice
#Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(value = {Exception.class})
public ResponseEntity<Object> handleGenericExceptions(Exception exception, WebRequest webRequest) {
log.error("Handling: ", exception);
HttpStatus errorCode = HttpStatus.INTERNAL_SERVER_ERROR;
return this.handleExceptionInternal(exception, new ErrorInfo(errorCode.value(), "Unexpected Internal Server Error"), new HttpHeaders(), errorCode, webRequest);
}
}
You can read more about error handling in Spring Boot at https://www.baeldung.com/exception-handling-for-rest-with-spring.

Spring 5 exception handling - ResponseStatusException model

I was reading the article - https://www.baeldung.com/exception-handling-for-rest-with-spring
which says
Spring 5 introduced the ResponseStatusException class.
We can create an instance of it providing an HttpStatus and optionally
a reason and a cause:
I started implementing it , and the code is
custom exception
#ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Actor Not Found")
public class ActorNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public ActorNotFoundException(String errorMessage) {
super(errorMessage);
}
}
method in service
public String updateActor(int index, String actorName) throws ActorNotFoundException {
if (index >= actors.size()) {
throw new ActorNotFoundException("Actor Not Found in Repsoitory");
}
actors.set(index, actorName);
return actorName;
}
controller
#GetMapping("/actor/{id}")
public String getActorName(#PathVariable("id") int id) {
try {
return actorService.getActor(id);
} catch (ActorNotFoundException ex) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Actor Not Found", ex); //agreed it could be optional, but we may need original exception
}
}
repo:
https://github.com/eugenp/tutorials/tree/master/spring-5/src/main/java/com/baeldung/exception
Question:
why ResponseStatusException in controller again has to specify reason - "Actor Not Found" ?, as the service already said - ""Actor Not Found in Repsoitory"
What is the proper way to adapt to ResponseStatusException model?
It looks like a mistake. Ideally the service shouldn't use any HTTP code, so I would remove the annotation in ActorNotFoundException. Everything else seems fine, the exception is caught in the controller and ResponseStatusException is thrown which is good, because it's a proper layer to put HTTP stuff.
Overall it is better to use #ControllerAdvice instead of ResponseStatusException. it gives you a unified exception handling solution. Although it is not a good idea from a design point of view, ResponseStatusException can help you to avoid creating your custom exceptions and use it at the service level to throw in case of an Exception.
to avoid writing the message again you can use the message that is already available in thrown exception:
throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage() , ex);
for examples and more info you can refer to the following articles:
Spring Boot Exception Handling — #ControllerAdvice
Spring Boot Exception Handling — ResponseStatusException

How to send error message with restfulAPI using SpringBoot

I have server which is built using SpringBoot and restful api's. It is simple CRUD application.
I am trying to check if email already exists while adding a new user.
I am not sure how to send error messages over rest api. I have tried like this:
UserController.java
//POST method for adding one user
#PostMapping("/addUser")
public ResponseEntity<User> addUser(#RequestBody User user){
User existingUser = userRepository.findByEmail(user.getEmail());
if(existingUser != null){
throw new UserAlreadyExistException("User with this email already exists");
}
return new ResponseEntity<>(service.saveUser(user), HttpStatus.OK) ;
}
UserAlreadyExistException.java
public class UserAlreadyExistException extends RuntimeException{
public UserAlreadyExistException(String message) {
super(message);
}
}
When I test it with Postman I get Error: 500 Internal Server Error
And in InteliJ I have this exception thrown:
com.example.library.UserAlreadyExistException: User with this email
already exists
Is this a correct way to do it or what is the best practice?
What you're looking for is #ControllerAdvice and #ExceptionHandler. The way such exceptions are handled is:
Create a global exception handler and annotate with #ControllerAdvice
Catch your exception using #ExceptionHandler in one of the methods specific to a certain exception.
So, adding below code will catch the exception and return custom response.
#ControllerAdvice
public class GlobalExceptionHandler {
#ExceptionHandler
public ResponseEntity<Object> handleAuthenticationException(UserAlreadyExistException e) {
// do what you want with e
return new ResponseEntity<>("User already exists", HttpStatus.OK);
}

Prevent spring errors on webpage

I am using spring MVC 3.
I validate various users input and show errors as applicable.
But this often to show the spring errors like org.springframework.core.convert.ConversionFailedException etc being shown on UI. How can i prevent the output of these errors on webpage ?
Note:
I understand that for topic starter my answer may be no longer
relevant. But it can be useful for those who have visited this page to
search for solutions to similar problems.
Answer:
In order to prevent the output of errors on web page, you may handle them. There are several types of error handling, that you may use for this in Spring MVC 3.x and above:
Controller-based exception handling
Global exception handling
Other methods, that are bit more complicated
Controller-based exception handling
You can add an #ExceptionHandler annotation on methods inside a controller. Such methods will function as error handlers for exceptions thrown from methods annotated as #RequestMapping in the same controller.
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", req.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
Global exception handling
A controller advice allows you to apply exception handling across the whole application, not just to an individual controller. In other words, handling will apply to exceptions thrown from any controller.
#ControllerAdvice
class GlobalControllerExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
#ExceptionHandler(Exception.class)
public void handleError(HttpServletRequest req, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", req.getRequestURL());
modelAndView.setViewName(DEFAULT_ERROR_VIEW);
return modelAndView;
}
}
For more info:
Exception Handling in Spring MVC

#ExceptionHandler in Spring

In my application I have configured an error page in web.xml. I need to override that for a specific controller based on a condition. Here when a condition becomes true I need to redirect to a specific error page otherwise normal error page should be rendered.
Here is the code. Please help me.
#Controller
public class Test{
#ExceptionHandler(Exception.class)
public ModelAndView generateException(HttpServletRequest httpServletRequest){
if(condition) {
return new ModelAndView("myError.jsp");
} else {
//should execute default error page.
}
}
}
Throw the exception again which will be handled by DefaultHandlerExceptionResolver to respond with the error page defined in your web.xml; It doesn't invoke the same Exception Handler of the controller.
#ExceptionHandler(Exception.class)
public ModelAndView generateException(Exception ex) throws Exception{
if(condition) {
return new ModelAndView("myError.jsp");
} else {
//should execute default error page.
throw ex;
}
}

Resources