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 SpringBoot

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article focuses on "how to handle SpringBoot custom exceptions". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "SpringBoot custom exception handling" bar!

i. Environment building

First of all, you have to build a web application before it is possible to continue the follow-up testing. Building a web application with SpringBoot is a relatively simple task.

Create a maven project with the following pom file

Org.springframework.boot spring-boot-starter-parent 2.1.7 UTF-8 UTF-8 Finchley.RELEASE 1.8 org.springframework.boot spring-boot-starter-web com.alibaba fastjson 1.2.45 org.springframework.boot spring-boot-maven-plugin Spring-milestones Spring Milestones https://repo.spring.io/milestone false II. HandlerExceptionResolver1. Custom exception handling

As the name implies, HandlerExceptionResolver is a class that handles exceptions. The interface is a method, and the callback after the exception occurs. Exception stack information is also carried in the four parameters.

@ NullableModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, @ Nullable Object handler, Exception ex)

It is relatively simple to customize the exception handling class, implement the above interface, and then return the complete stack to the caller

Public class SelfExceptionHandler implements HandlerExceptionResolver {@ Override public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {String msg = GlobalExceptionHandler.getThrowableStackInfo (ex); try {response.addHeader ("Content-Type", "text/html; charset=UTF-8"); response.getWriter () .append ("Custom exception handling!!\ n") .append (msg) .flush () } catch (Exception e) {e.printStackTrace ();} return null;}} / / Stack information is printed as follows: public static String getThrowableStackInfo (Throwable e) {ByteArrayOutputStream buf = new ByteArrayOutputStream (); e.printStackTrace (new java.io.PrintWriter (buf, true)); String msg = buf.toString (); try {buf.close () } catch (Exception t) {return e.getMessage ();} return msg;}

Taking a closer look at the above code implementation, there are a few points to pay attention to

To ensure that the Chinese characters will not be garbled, we have set the backward response.addHeader ("Content-Type", "text/html; charset=UTF-8"). If there is no such line, the Chinese garbled will occur.

Our pure backend application does not want to return to the view, but directly wants to write data into the output stream of Response to return response.getWriter (). Append ("Custom exception handling!!\ n") .append (msg). Flush (); if there is a custom error page in the project, you can determine the final error page by returning ModelAndView

The above code does not take effect directly. You need to register it. You can register it in a subclass of WebMvcConfigurer. The example is as follows

SpringBootApplicationpublic class Application implements WebMvcConfigurer {@ Override public void configureHandlerExceptionResolvers (List resolvers) {resolvers.add (0, new SelfExceptionHandler ());} public static void main (String [] args) {SpringApplication.run (Application.class);}} 2. Test case

We still use the use case from the previous blog post to test

@ Controller@RequestMapping (path = "page") public class ErrorPageRest {@ ResponseBody @ GetMapping (path = "divide") public int divide (int sub) {return 1000 / sub;}}

The following are the measured results of 404 and 500 anomalies, respectively.

500 exceptions will enter our custom exception handling class, while 404 still goes to the default error page, so if we need to catch 404 exceptions, we still need to add them to the configuration file

# when an error occurs, directly throw an exception spring.mvc.throw-exception-if-no-handler-found=true# to set the static resource mapping access path spring.mvc.static-path-pattern=/statics/**# spring.resources.add-mappings=false

Why does 404 need extra processing?

Let's try to explain this problem in an easy-to-understand way

Java web applications, in addition to returning json class data, may also return web pages, js,css

We use @ ResponseBody to indicate that a url returns json data (usually this is the case, regardless of custom implementation)

The REST service defined by @ RequestMapping in our @ Controller returns static resources

Well, js,css, pictures, these files, in our web application, will not define a REST service.

So when a http request is received and the url association mapping cannot be found, it is not considered to be a NoHandlerFoundException by default. Instead of throwing an exception, it is found in the static resource (not in the static resource either, why not throw the NoHandlerFoundException? This exception indicates that the url request does not have a corresponding processor, but here we have assigned it a static resource processor ResourceHttpRequestHandler)

For the above point, if you are interested in digging deeply, the key code location is given here.

/ / entry method: `org.springframework.web.servlet.DispatcherServlet# doDispatch` / / debug node Determine handler for the current request.mappedHandler = getHandler (processedRequest); if (mappedHandler = = null) {noHandlerFound (processedRequest, response); return } / / Core logic / / org.springframework.web.servlet.DispatcherServlet#getHandler@Nullableprotected HandlerExecutionChain getHandler (HttpServletRequest request) throws Exception {if (this.handlerMappings! = null) {for (HandlerMapping hm: this.handlerMappings) {if (logger.isTraceEnabled ()) {logger.trace ( "Testing handler map [" + hm + "] in DispatcherServlet with name'" + getServletName () + "'") } HandlerExecutionChain handler = hm.getHandler (request); if (handler! = null) {return handler;} return null } at this point, I believe you have a deeper understanding of "SpringBoot custom exception handling". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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