Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to handle custom exceptions in Spring Boot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to deal with custom exceptions in Spring Boot. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

In Spring Boot projects, unified exception handling can be done using @ ControllerAdvice in Spring, or you can define your own exception handling scheme. In Spring Boot, there are some default strategies for exception handling, which we'll look at separately.

By default, the exception page in Spring Boot looks like this:

From this exception prompt, we can also see that the reason why users see this page is that the developer does not explicitly provide a / error path. If the developer provides a / error path, the page will not be displayed. However, in Spring Boot, providing / error path is actually the worst policy. When Spring Boot itself handles exceptions, it will only look for / error path when all conditions are not met. So let's first take a look at, in Spring Boot, how to customize error pages, on the whole, can be divided into two types, one is static pages, the other is dynamic pages.

Static exception page

Custom static exception page, and divided into two types, the first is to use HTTP response code to name the page, such as 404.html, 405.html, 500.html...., the other is to directly define a 4xx.html, indicating that the status of 400,499 shows this exception page, 5xx.html indicates that the status of 500,599 shows this exception page.

By default, the relevant page is defined under the classpath:/static/error/ path:

At this point, start the project, if the project throws a 500request error, the 500.html page will be automatically displayed, and the 404.html page will be displayed when 404 occurs. If there are both 5xx.html and 500.html in the exception display page, the 500.html page will be displayed first when an exception occurs.

Dynamic exception page

The dynamic exception page definition is basically the same as the static one, and the page templates that can be used are jsp, freemarker and thymeleaf. Dynamic exception pages also support 404.html or 4xx.html, but generally speaking, since dynamic exception pages can directly display the details of exceptions, there is no need to enumerate errors one by one. Just define 4xx.html (thymeleaf template is used here) or 5xx.html.

Note that the dynamic page template does not require developers to define the controller themselves, but can directly define the exception page. The exception handler included in Spring Boot will automatically find the exception page.

The page is defined as follows:

The page content is as follows:

Title5xx path error message timestamp status

By default, these 5 items are the complete exception information, and the results are as follows:

If both dynamic and static pages define exception handling pages, such as when classpath:/static/error/404.html and classpath:/templates/error/404.html exist at the same time, dynamic pages are used by default. That is, the complete error page search method should be as follows:

A 500th error occurred-- > find dynamic 500.html page-- > find static 500.html-- > find dynamic 5xx.htl 5xx.html-> find static XML.

Custom exception data

By default, in Spring Boot, all the exception data is actually the five pieces of data shown above, which are defined in the org.springframework.boot.web.reactive.error.DefaultErrorAttributes class and specifically in the getErrorAttributes method:

Overridepublic Map getErrorAttributes (ServerRequest request, boolean includeStackTrace) {Map errorAttributes = new LinkedHashMap (); errorAttributes.put ("timestamp", new Date ()); errorAttributes.put ("path", request.path ()); Throwable error = getError (request); HttpStatus errorStatus = determineHttpStatus (error); errorAttributes.put ("status", errorStatus.value ()); errorAttributes.put ("error", errorStatus.getReasonPhrase ()) ErrorAttributes.put ("message", determineMessage (error)); handleException (errorAttributes, determineException (error), includeStackTrace); return errorAttributes;}

The DefaultErrorAttributes class itself is defined in the org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration exception autoconfiguration class. If the developer does not provide an instance of ErrorAttributes, then Spring Boot will automatically provide an instance of ErrorAttributes, that is, DefaultErrorAttributes.

Based on this, developers can customize ErrorAttributes in two ways:

Directly implement the ErrorAttributes interface

Inherit DefaultErrorAttributes (recommended) because the handling of exception data in DefaultErrorAttributes has been completed and developers can use it directly.

The specific definition is as follows:

@ Componentpublic class MyErrorAttributes extends DefaultErrorAttributes {@ Override public Map getErrorAttributes (WebRequest webRequest, boolean includeStackTrace) {Map map = super.getErrorAttributes (webRequest, includeStackTrace); if ((Integer) map.get ("status") = = 500) {map.put ("message", "server internal error!");} return map;}}

The defined ErrorAttributes must be registered as a Bean, so that Spring Boot will not use the default DefaultErrorAttributes, as shown below:

Custom exception view

The default exception view is the static or dynamic page mentioned above, which can also be customized. First of all, the default exception view loading logic is in the errorHtml method of the org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController class, which is used to return exception page + data, as well as another error method, which is used to return exception data (if it is an ajax request, the method will be triggered).

RequestMapping (produces = MediaType.TEXT_HTML_VALUE) public ModelAndView errorHtml (HttpServletRequest request, HttpServletResponse response) {HttpStatus status = getStatus (request); Map model = Collections.unmodifiableMap (getErrorAttributes (request, isIncludeStackTrace (request, MediaType.TEXT_HTML)); response.setStatus (status.value ()); ModelAndView modelAndView = resolveErrorView (request, response, status, model); return (modelAndView! = null)? ModelAndView: new ModelAndView ("error", model);}

In this method, you will first get the exception data through the getErrorAttributes method (actually call the getErrorAttributes method of the instance of ErrorAttributes), and then call resolveErrorView to create a ModelAndView. If the creation fails here, the user will see the default error page.

Normally, the resolveErrorView method comes to the resolveErrorView method of the DefaultErrorViewResolver class:

Overridepublic ModelAndView resolveErrorView (HttpServletRequest request, HttpStatus status, Map model) {ModelAndView modelAndView = resolve (String.valueOf (status.value ()), model); if (modelAndView = = null & & SERIES_VIEWS.containsKey (status.series () {modelAndView = resolve (SERIES_VIEWS.get (status.series ()), model);} return modelAndView;}

Here, we first use the exception response code as the view name to find dynamic pages and static pages, and if not, then use 4xx or 5xx as the view name to find dynamic or static pages respectively.

It is also easy to customize the exception view resolution. Since DefaultErrorViewResolver is an instance provided in the ErrorMvcAutoConfiguration class, that is, when the developer does not provide the relevant instance, the default DefaultErrorViewResolver will be used. After the developer provides his own ErrorViewResolver instance, the default configuration will become invalid. Therefore, to customize the exception view, you only need to provide an instance of ErrorViewResolver:

@ Componentpublic class MyErrorViewResolver extends DefaultErrorViewResolver {public MyErrorViewResolver (ApplicationContext applicationContext, ResourceProperties resourceProperties) {super (applicationContext, resourceProperties);} @ Override public ModelAndView resolveErrorView (HttpServletRequest request, HttpStatus status, Map model) {return new ModelAndView ("/ aaa/123", model);}}

In fact, developers can also define exception data here (redefine a model directly in the resolveErrorView method, copy the model data in the parameter and modify it. Note that the model type in the parameter is UnmodifiableMap, that is, it cannot be modified directly) without the need for custom MyErrorAttributes. After the definition is complete, provide a view named 123, as shown below:

After that, the error attempt is considered to be successful.

This is the end of this article on "how to handle custom exceptions in Spring Boot". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report