乐闻世界logo
搜索文章和话题

How can you customize the default error pages in a Spring Boot application?

1个答案

1

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

  1. Create a class implementing the ErrorController interface: Spring Boot provides the ErrorController interface, which you can implement to customize error handling.

    java
    import 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"; } }
  2. Define error pages: Create error pages in the src/main/resources/templates directory, such as error-404.html, error-500.html, and error.html.

  3. Configuration: Ensure your project includes a template engine, such as Thymeleaf.

Method Two: Customizing Error Information with ErrorAttributes

  1. Customize ErrorAttributes: You can provide a custom ErrorAttributes to customize error information.

    java
    import 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; } }
  2. Register CustomErrorAttributes: Register this custom ErrorAttributes in your configuration class.

    java
    import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ErrorConfig { @Bean public CustomErrorAttributes errorAttributes() { return new CustomErrorAttributes(); } }
  3. 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.

2024年8月7日 22:13 回复

你的答案