In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "the use of SpringBoot global exception handling", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to use SpringBoot global exception handling".
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
It's still a normal process. After the pom dependency is done, write a program entry.
/ * Created by @ author yihui in 15:26 19-9-13. * / @ SpringBootApplicationpublic class Application {public static void main (String [] args) {SpringApplication.run (Application.class);}} II. Exception handling 1. @ ControllerAdvice
We usually use @ ControllerAdvice with the annotation @ ExceptionHandler to achieve global exception capture handling
@ ControllerAdvice weaves enhancement methods for all Controller
The @ ExceptionHandler tag on the method indicates that the method will be triggered when the corresponding exception is thrown to the upper layer (that is, it is not caught by the business)
Let's demonstrate the function through an example.
a. Exception capture
We define two exception-caught case, one is divided by 0, and the other is an array out of bounds exception
@ Slf4j@ControllerAdvicepublic class GlobalExceptionHandler {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 } @ ResponseBody @ ExceptionHandler (value = ArithmeticException.class) public String handleArithmetic (HttpServletRequest request, HttpServletResponse response, ArithmeticException e) throws IOException {log.info ("divide error!"); return "divide 0:" + getThrowableStackInfo (e) @ ResponseBody @ ExceptionHandler (value = ArrayIndexOutOfBoundsException.class) public String handleArrayIndexOutBounds (HttpServletRequest request, HttpServletResponse response, ArrayIndexOutOfBoundsException e) throws IOException {log.info ("array index out error!"); return "aryIndexOutOfBounds:" + getThrowableStackInfo (e);}}
In the above test, we returned the exception stack to the caller
b. Sample service
Add several test methods
@ Controller@RequestMapping (path = "page") public class ErrorPageRest {@ ResponseBody @ GetMapping (path = "divide") public int divide (int sub) {return 1000 / sub;} private int [] ans = new int [] {1,2,3,4}; @ ResponseBody @ GetMapping (path = "ary") public int ary (int index) {return ans [index];}} c. Test description
The example test is as follows. Above, we declare that the two exceptions caught are intercepted and output the corresponding stack information.
But you need to pay attention.
404 and uncaught 500exceptions display the SpringBoot default error page
In addition, the http status code returned by our capture is 200.
2. @ ResponseStatus
The status code returned by the exception caught in the case above is 200, but in some case, you may prefer to return a more appropriate http status code, which can be specified using ResponseStatus
The way to use it is relatively simple, just add a note
@ ResponseBody@ExceptionHandler (value = ArithmeticException.class) @ ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR) public String handleArithmetic (HttpServletRequest request, HttpServletResponse response, ArithmeticException e) throws IOException {log.info ("divide error!"); return "divide 0:" + getThrowableStackInfo (e);}
3. 404 processing
With @ ControllerAdvice and @ ExceptionHandler, I can block 500. what can I do if I want 404 exceptions to be intercepted as well?
First modify the configuration file application.properties to throw out the NoHandlerFoundException
# 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. Choose one of the following two, spring.mvc.static-path-pattern=/statics/**# spring.resources.add-mappings=false
The second is to define exception catch
@ ResponseBody@ExceptionHandler (value = NoHandlerFoundException.class) @ ResponseStatus (HttpStatus.NOT_FOUND) public String handleNoHandlerError (NoHandlerFoundException e, HttpServletResponse response) {return "noHandlerFound:" + getThrowableStackInfo (e);}
Tested again as follows, 404 was captured by us and returned stack information
At this point, I believe you have a deeper understanding of "the use of SpringBoot global 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.
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.