Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I create an error handler (404, 500...) in Spring Boot/MVC

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";
    }

}
like image 839
Ismael Ezequiel Avatar asked Aug 04 '16 21:08

Ismael Ezequiel


People also ask

How does Spring MVC handle 404 error?

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.

How do I create a 404 page in spring boot?

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.

How exceptions are handled in MVC Spring?

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.

What is 500 error in spring boot?

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.


1 Answers

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");
    }
}
like image 99
Dr. Mehmet Ali ATICI Avatar answered Nov 11 '22 20:11

Dr. Mehmet Ali ATICI