Error pages based on spring thymeleaf controller

I managed to create static error pages and redirect them using this bean:

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {

        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                if (optiuniEnvironment.equals("development")) {
                    ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
                    ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
                    ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/404.html");

                    container.addErrorPages(error401Page, error404Page, error500Page);
                }
            }
        };
    }

      

However, now I want to create a custom page that uses the functionality of the controller.

So, in my controller, I have something like

    @RequestMapping("/404.html")
    String pageNotFound(Model model, HttpServletRequest request)
    {
        return "404";
    }

      

and want to redirect it if I encounter HttpStatus 404.

I believe the answer is configuring the DispatcherServlet, but not sure. Any ideas? Thank!

(if possible, use java config and not xml)

+2


source to share


2 answers


Solution for SpringBoot version: 1.2 - even if not the best - so far it's good enough.

Created by GlobalErrorController

@RestController
@Profile("prod")
public class GlobalErrorController implements ErrorController {

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public void error(HttpServletResponse response) throws IOException {
        int status = response.getStatus();
        switch (status) {
            case 404:
                response.sendRedirect("/404");
                break;
            case 401:
                response.sendRedirect("/401");
                break;
            case 403:
                response.sendRedirect("/401");
                break;
            default:
                response.sendRedirect("/404");
        }

    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

      

And in my HomeController I added:



@RequestMapping("404")
String get404ErrorPage() {
    return "404";
}

@RequestMapping("401")
String get401ErrorPage() {
    return "401";
}

      

I chose this approach because I need some functionality from the controller in the error pages.

More solutions are more than welcome!

0


source


You can handle these errors using the following methods:

1. Using an exception handler method in one controller:

@ExceptionHandler(NoHandlerFoundException.class)
public String handle404Exception(NoHandlerFoundExceptionex) {
     //do whatever you want
     return "viewName";
}

      

2. Create an exception controller

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handle404Exception(NoHandlerFoundExceptionex) {
         //do whatever you want
         return "viewName";
    }
}

      



When using Spring Boot, set the following properties in application.properties

server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

      

3. Adding an error logger:

@Bean
public ErrorPageRegistrar errorPageRegistrar(){
    return new CustomErrorPageRegistrar();
}

private static class CustomErrorPageRegistrar implements ErrorPageRegistrar {

    // Register your error pages and url paths.
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
    }

}

      

and define the controller endpoint for the corresponding urls (e.g. / 400)

+3


source







All Articles