There are two primary methods to customize default error pages in Spring Boot: by implementing the ErrorController interface or by utilizing ErrorAttributes to customize error information. Below are detailed steps and examples:
Method One: Implementing the ErrorController Interface
-
Create a class implementing the
ErrorControllerinterface: Spring Boot provides theErrorControllerinterface, which you can implement to customize error handling.javaimport org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; @Controller public class MyCustomErrorController 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 "error-404"; } else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) { return "error-500"; } } return "error"; } @Override public String getErrorPath() { return "/error"; } } -
Define error pages: Create error pages in the
src/main/resources/templatesdirectory, such aserror-404.html,error-500.html, anderror.html. -
Configuration: Ensure your project includes a template engine, such as Thymeleaf.
Method Two: Customizing Error Information with ErrorAttributes
-
Customize
ErrorAttributes: You can provide a customErrorAttributesto customize error information.javaimport org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.web.context.request.WebRequest; public class CustomErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace); errorAttributes.put("message", "This is a customized error message."); return errorAttributes; } } -
Register
CustomErrorAttributes: Register this customErrorAttributesin your configuration class.javaimport org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ErrorConfig { @Bean public CustomErrorAttributes errorAttributes() { return new CustomErrorAttributes(); } } -
Error pages: Similarly, you need to prepare the corresponding error pages in your project.
By using these two methods, you can flexibly handle and display error information, improving the friendliness and professionalism of your application.