Question

Customizing the error page based on the status instead of Tomcat default page with springboot

Not able to redirect the error in the custom page.

Configuration:

server:
  error:
    whitelabel:
      enabled: false
    path: /error

spring:
  web:
    resources:
      add-mappings: false
@RestController
@RequiredArgsConstructor
public class CustomErrorController implements ErrorController {
  private static final String PATH = "/error";

  @RequestMapping("/error")
  public String handleError(HttpServletRequest request) {
    Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

    if (status != null) {
      Integer statusCode = Integer.valueOf(status.toString());

      if (statusCode == HttpStatus.NOT_FOUND.value()) {
        return "error-404";
      } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
        return "error-500";
      }
    }
    return "error";
  }
}
 4  29  4
1 Jan 1970

Solution

 1

your annotations are wrong, it should be @Controller, not @RestController - because you resolving a page, not returning a resource

2024-07-15
J Asgarov

Solution

 1

You don't need any of this. DItch your controller and just add an 404.html in your src/main/resources/templates/error. Which works for ranges as well by adding a 4xx.html or 5xx.html etc. This is for Thymeleaf, same works for other view technologies as well.

You can also put them in src/main/resources/public/error and as static html.

This is build into Spring Boot (which you would have found if you read the documentation)

2024-07-15
M. Deinum