Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
  }
}
like image 833
Rupesh Sunuwar Avatar asked Oct 20 '25 11:10

Rupesh Sunuwar


2 Answers

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

like image 173
asgarov1 Avatar answered Oct 22 '25 01:10

asgarov1


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)

like image 26
M. Deinum Avatar answered Oct 22 '25 01:10

M. Deinum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!