11-SpringBoot Exception handling in engineering
Background analysis
In the development of the project , Regardless of the underlying data logic operation process , Or the process of business logic , Or the process of control logic , It's inevitable to encounter all kinds of predictable 、 Unpredictable anomalies . Handling the exception has a good protection effect on the system , At the same time, it will greatly improve the user experience .
Exception handling analysis
summary
Java There are two ways to handle exceptions in a project , Or execute trycatch operation , Or execute throw operation ( Throw it to other objects ), Either way , The goal is for our system to have feedback on anomalies . But now the question is how to make this feedback code simple and intuitive 、 friendly .
Treatment specification
We usually have to follow certain design specifications when dealing with exceptions , for example :
- When an exception is caught, it must exactly match the exception thrown , Or catch exception is the parent type of the exception thrown .
- Avoid direct selling RuntimeException, You're not allowed to throw it Exception perhaps Throwable, Custom exceptions with business meaning should be used ( for example ServiceException).
- After the exception is caught, it must be handled ( For example, keep a log ). If you don't want to deal with it , You need to throw the exception to its caller .
- The outermost logic must handle exceptions , Turn it into something that users can understand .
- Avoid duplicate code (Don’t Repeat Yourself), namely DAY principle .
SpringBoot Exception handling under engineering
preparation
First step : Create or project module, And add web rely on , The code is as follows :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The second step : Modify the project access port to 80, for example
server.port=80
The third step : Definition Controller class , The code is as follows :
package com.cy.pj.arithmetic.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ArithmeticController {
@RequestMapping("doCompute/{n1}/{n2}")
@ResponseBody
public String doCompute(@PathVariable Integer n1,
@PathVariable Integer n2){
Integer result=n1/n2;
return "Result is "+result;
}
}
Step 4 start the project for access testing
Type in the browser address bar http://localhost/doCompute/10/2, Test the output .
Result is 5
Default exception handling
Type in the browser address bar http://localhost/doCompute/10/0, Test the output .
For such default exception handling (spring boot Provide ), The user experience is not very friendly , In order to present more friendly exception information , We usually have to customize the exception handling .
own try exception handling
In the control layer approach , We can do it try catch Handle , for example :
@RequestMapping("doCompute/{n1}/{n2}")
@ResponseBody
public String doCompute(@PathVariable Integer n1,
@PathVariable Integer n2){
try{
Integer result=n1/n2;
return "Result is "+result;
}catch(ArithmeticException e){
return "exception is "+e.getMessage();
}
}
One Controller There are usually multiple methods in a class , It's written in all of these methods try Statement exception handling will bring a lot of repetitive code writing , Difficult to maintain .
Controller Internally define exception handling methods
stay Controller Class to add exception handling methods , The code is as follows :
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public String doHandleArithmeticException(ArithmeticException e){
e.printStackTrace();
return " An exception occurred during the calculation , The exception information is "+e.getMessage();
}
@ExceptionHandler The method described by the annotation is exception handling method ( Exception types in annotations are exception types that can be handled ), If Controller The exception is not handled after an exception occurs in a logical method in the class , Will find Controller Is there an exception handling method defined in the class , If we define , And can handle the type of exception thrown , The exception handling method handles the exception .
Global exception handling class and method definition in control layer
When an item is defined by a method that has more than one common exception in multiple control layer classes , We can extract these methods into common parent objects , But this approach is a strongly coupled implementation , Not conducive to code maintenance . We can also use spring In the frame web Module defined global exception handling specification , For example, define a global exception handling class , The code is as follows :
package com.cy.pj.common.web;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ArithmeticException.class)
public String doHandleArithmeticException(ArithmeticException e){
e.printStackTrace();
return " An exception occurred during the calculation , The exception information is "+e.getMessage();
}
}
among ,@RestControllerAdvice The class described by the annotation is a global exception handling class , When the exception in the control layer method is not caught by itself , There is no definition of its internal exception handling method , By default, the underlying layer looks for global exception handling classes , Call the corresponding exception handling method for exception handling . As shown in the figure :
summary (Summary)
This section is mainly about springboot The exception handling mechanism in is analyzed and explained . The purpose is to master springboot Exception handling in engineering , And based on the different business response exception handling . So as to effectively improve its user experience , Enhance the fault tolerance of the system .