spring-boothttphttpresponsecustom-error-pages

How to redirect http errors response? - Custom Error Page


I am working on a web app with springboot, I want to be able to redirect the user when requesting a page that doesn't exist.

I've tried following this guide :https://www.baeldung.com/spring-boot-custom-error-page

But it's not working as expected, the "/error" page works, but If I try to access a path that doesn't exists I get the usual message:

{"type":"about:blank","title":"Not Found","status":404,"detail":"No static resource randomURL.","instance":"/randomURL"}

I would like to get either my custom "404.html" or be redirected to the main page!


Solution

  • First, please confirm that you have added thymeleaf to your pom.xml like this:

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    

    Then, ensure that you have added the corresponding HTML files as described at https://www.baeldung.com/spring-boot-custom-error-page, like this: 12

    Lastly, you only need to add a custom controller and implement ErrorController like this:

    @Controller
    public class CustomErrorController implements ErrorController {
    
        @RequestMapping("/error")
        public String handleError(HttpServletRequest request) {
            Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
            if (status != null) {
                int statusCode = Integer.parseInt(status.toString());
                if (statusCode == HttpStatus.NOT_FOUND.value()) {
                    return "404";
                } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                    return "500";
                }
            }
            return "error";
        }
    }
    
    

    3