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";
}
}
The 404 error code is configured properly, but it will caused the “. htm” extension handling conflict between the “servlet container” and Spring's “DispatcherServlet“. To solve it, try change the 404. htm to other file extension, for example 404.
We first need to create a custom HTML error page. If we save this file in resources/templates directory, it'll automatically be picked up by the default Spring Boot's BasicErrorController. We can be more specific by naming the file with the HTTP status code we want it used e.g. saving the file as 404.
Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.
The status and error message - 500 - indicates that something is wrong with our server code but actually it's a client error because the client provided an invalid id.
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With