Question
For some hours I'm trying to create a custom global error handler in Spring Boot/MVC. I've read a lot of articles and nothing.
That is my error class:
I tried create a class like that
@Controller
public class ErrorPagesController {
@RequestMapping("/404")
@ResponseStatus(HttpStatus.NOT_FOUND)
public String notFound() {
return "/error/404";
}
@RequestMapping("/403")
@ResponseStatus(HttpStatus.FORBIDDEN)
public String forbidden() {
return "/error/403";
}
@RequestMapping("/500")
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String internalServerError() {
return "/error/500";
}
}
Answer
You may try the following code:
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest request, Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
return new ModelAndView("error");
}
@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handleError404(HttpServletRequest request, Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
return new ModelAndView("404");
}
}