In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "SpringBoot how to customize error pages and error data". In daily operation, I believe many people have doubts about how to customize error pages and error data in SpringBoot. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to customize error pages and error data by SpringBoot". Next, please follow the editor to study!
We know that Spring Boot already provides a default exception handling mechanism, but the default exception handling mechanism provided by Spring Boot is not necessarily suitable for our actual business scenarios. Therefore, we usually customize Spring Boot global exceptions according to our own needs, such as customizing error pages, customizing error data, and so on.
Customize the error page
We can customize the Spring Boot error page in three ways:
Custom error.html
Customize the dynamic error page
Customize the static error page
Custom error.html
We can create an error.html directly under the template engine folder (/ resources/templates), overriding the Spring Boot default error view page (Whitelabel Error Page).
Example 1
1. Under the template engine folder (classpath:/resources/templates) of spring-boot-adminex, create an error.html as follows.
Custom error.html Custom error.html
Status:
Error:
Timestamp:
Message:
Path:
two。 Start Spring Boot, after completing the login jump to the home page, use the browser to visit "http://localhost:8080/111"", the result is shown below.
Figure 1: custom error.html
As you can see from figure 1, Spring Boot overrides the default error view page (Whitelabel Error Page) with our custom error.html.
Customize the dynamic error page
If the Sprng Boot project uses a template engine, Spring Boot's default error view parser (DefaultErrorViewResolver) parses the error view page in the error directory in the template engine folder (resources/templates/) when an exception occurs in the program.
Exact matching
We can create different dynamic error pages (such as 404.html, 500.html, 400.html, etc.) according to the error status codes (for example, 404,500,400, etc.) and store them in the error directory under the template engine folder. When an exception occurs, Spring Boot will match exactly to the corresponding error page according to its error status code.
Example 2
1. In the error directory under the template engine folder of spring-boot-adminex, create an error page named 404.html as follows.
Customize the dynamic error page 404.html
Status:
Error:
Timestamp:
Message:
Path:
two。 Start Spring Boot, and after completing the login jump to the home page, type "http://localhost:8080/111"" in the browser address bar, and the result is as shown below.
Figure 2: custom dynamic error page (exact match)
Fuzzy matching
We can also use 4xx.html and 5xx.html as the file names of the dynamic error page, and store them in the error directory under the template engine folder to vaguely match all errors of the corresponding type. For example, all exceptions with error status codes starting with "4" will be resolved to the dynamic error page 4xx.html.
Example 3
In the error directory under the template engine folder of spring-boot-adminex, create an error page named 4xx.html as follows.
Customize the dynamic error page 4xx.html
Status:
Error:
Timestamp:
Message:
Path:
two。 Start Spring Boot, after completing the login to jump to the home page, use the browser to visit "http://localhost:8080/111"", the result is shown below.
Figure 3: custom dynamic error page (fuzzy match)
Customize the static error page
If the Sprng Boot project does not use a template engine, when an exception occurs in the program, Spring Boot's default error view parser (DefaultErrorViewResolver) parses the static error page in the error directory under the static resource folder.
Exact matching
We can create different static error pages (such as 404.html, 500.html, 400.html, etc.) depending on the error status codes (for example, 404,500,400, and so on) and store them in the error directory under the static resource folder. When an exception occurs, Spring Boot will match exactly to the corresponding error page according to the error status code.
Example 4
1. In the error directory under spring-boot-adminex 's static resource folder src/recources/static, create a static error page named 404.html as follows.
Customize the static error page 404.html
Status:
Error:
Timestamp:
Message:
Path:
two。 Start Spring Boot, after completing the login to jump to the home page, use the browser to visit "http://localhost:8080/111"", the result is shown below.
Figure 3: custom static error page (exact match)
Because the error page is static, the Thymeleaf expression is not recognized, so the error message associated with the error cannot be displayed.
Fuzzy matching
We can also use 4xx.html and 5xx.html as the file names of the static error page and store them in the error directory under the static resource folder to vaguely match all errors of the corresponding type. For example, all errors with error status codes starting with "4", such as 404,400, will be resolved to the static error page 4xx.html.
Example 3
In the error directory under the template engine folder of spring-boot-adminex, create an error page named 4xx.html as follows.
Customize the static error page 4xx.html
Status:
Error:
Timestamp:
Message:
Path:
two。 Start Spring Boot, after completing the login to jump to the home page, use the browser to visit "http://localhost:8080/111"", the result is shown below.
Figure 3: custom static error page (fuzzy match)
Error page priority
Spring Boot error pages can be customized in the above five ways, and their priority order is: custom dynamic error page (exact match) > custom static error page (exact match) > custom dynamic error page (fuzzy match) > custom static error page (fuzzy match) > custom error.html.
When an error is encountered, Spring Boot will look for and resolve the error page according to the priority from high to low. Once the available error page is found, it will directly return to the client for display.
Customize error data
As we know, Spring Boot provides a default exception handling mechanism, and its main flow is as follows:
When an exception occurs, the request is forwarded to "/ error" and handed over to BasicErrorController (Spring Boot's default Error controller) for processing
BasicErrorController automatically adapts the response form returned according to the client. The browser client returns the error page and the machine client returns JSON data.
When BasicErrorController handles an exception, it calls the getErrorAttributes () method of DefaultErrorAttributes (the default error property handler) to get the error data.
We can also customize the error data for Spring Boot, as follows.
Customize the exception handling class, forward the request to "/ error", hand it over to the Spring Boot BasicErrorController for processing, and automatically adapt to the browser client and the machine client.
Define an error attribute handling tool by inheriting DefaultErrorAttributes, and add custom error data based on the original.
1. Custom exception handling class
Classes annotated by @ ControllerAdvice can be used to implement global exception handling, which is provided in Spring MVC and can be used directly in Spring Boot.
1) in the net.biancheng.net.exception package, create an exception class named UserNotExistException as follows.
Package net.biancheng.www.exception;/*** custom exception * / public class UserNotExistException extends RuntimeException {public UserNotExistException () {super ("user does not exist!") ;}}
2) add the following method to IndexController to trigger the UserNotExistException exception. The code is as follows.
@ Controllerpublic class IndexController {. @ GetMapping (value = {"/ testException"}) public String testException (String user) {if ("user" .equals (user)) {throw new UserNotExistException ();} / / Jump to login page login.html return "login";}}
3) in net.biancheng.www.controller, create a class called MyExceptionHandler exception handling with the following code.
Package net.biancheng.www.controller;import net.biancheng.www.exception.UserNotExistException;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import javax.servlet.http.HttpServletRequest;import java.util.HashMap;import java.util.Map;@ControllerAdvicepublic class MyExceptionHandler {@ ExceptionHandler (UserNotExistException.class) public String handleException (Exception e, HttpServletRequest request) {Map map = new HashMap () / pass the error status code request.setAttribute ("javax.servlet.error.status_code", 500) to the request object; / / Custom error data map.put ("code", "user.notexist"); map.put ("message", e.getMessage ()) based on the exception currently handled / / pass the custom error data to request.setAttribute ("ext", map) in the request domain; return "forward:/error";}} 2. Custom error attribute handling tool
1) in the net.biancheng.www.componet package, create an error attribute handling tool class MyErrorAttributes (inheriting DefaultErrorAttributes), through which we can add custom error data as follows.
Package net.biancheng.www.componet;import org.springframework.boot.web.error.ErrorAttributeOptions;import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;import org.springframework.stereotype.Component;import org.springframework.web.context.request.WebRequest;import java.util.Map;// adds a custom storage attribute handling tool @ Componentpublic class MyErrorAttributes extends DefaultErrorAttributes {@ Override public Map getErrorAttributes (WebRequest webRequest, ErrorAttributeOptions options) {Map errorAttributes = super.getErrorAttributes (webRequest, options) to the container / / add custom error data errorAttributes.put ("company", "www.biancheng.net"); / / get the error data passed into the request domain by MyExceptionHandler Map ext = (Map) webRequest.getAttribute ("ext", 0); errorAttributes.put ("ext", ext); return errorAttributes;}}
2) under the templates/error directory, create a dynamic error page 5xx.html as follows.
Custom error.html
Status:
Error:
Timestamp:
Message:
Path:
The following is customized error data:
Company:
Code:
Path:
3) start Spring Boot and visit "http://localhost:8080/testException?user=user"". The result is as shown below.
Figure 4: customizing error data
Note: in order to avoid the interference of the interceptor, it is recommended to block the interceptor first.
At this point, the study on "how to customize error pages and error data by SpringBoot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.