Wechat official account: If you have any questions or suggestions, please leave a message on the background. I will try my best to solve your problems.
preface
SpringBoot handles global exceptions in a unified manner. The two main annotations used for global exception handling in SpringBoot are @ControllerAdvice and @ExceptionHandler, where @ControllerAdvice is the component annotation. The class that added this annotation intercepts Controller requests, and the ExceptionHandler annotation sets the exception type in the global processing control to intercept the exception to be handled. For example, @ExceptionHandler(value = NullPointException.class).
The preparatory work
- SpringBoot 2.1.3
- IDEA
- JDK 8
Depend on the configuration
<dependencies>
<! -- JPA dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<! -- Web dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<! Mysql > connect to mysql
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<! -- Lombok dependency -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<! -- Unit test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Copy the code
The configuration file
spring:
# database related
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: JDBC: mysql: / / 127.0.0.1:3306 / test? useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update #ddl-auto: set to create to re-create the table each time
show-sql: true
Copy the code
The message class returned
public class Message<T> implements Serializable {
/** * Status code */
private Integer code;
/** * Returns a message */
private String message;
/** * Returns the data class */
private T data;
/** ** time */
private Long time;
// Getters, setters, and constructors
}
Copy the code
Utility class
For handling returned data and information classes, the code comments are not detailed.
public class MessageUtil {
/** * succeeds and returns the data entity class *@param o
* @param <E>
* @return* /
public static <E>Message<E> ok(E o){
return new Message<>(200."success", o, new Date().getTime());
}
/** * succeeded, but no data entity class returns *@return* /
public static <E>Message<E> ok(a){
return new Message<>(200."success".null.new Date().getTime());
}
/** * failed, custom exception returned *@param code
* @param msg
* @return* /
public static <E>Message<E> error(Integer code,String msg){
return new Message<>(code, msg, null.newDate().getTime()); }}Copy the code
Custom exception
By inheriting RuntimeException, declare code to define different types of custom exceptions. It is mainly used for exception interception to get the code and set the code to return in the message class.
public class CustomException extends RuntimeException{
/** * Status code */
private Integer code;
public Integer getCode(a) {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public CustomException(Integer code, String message){
super(message);
this.code = code; }}Copy the code
Exception blocking class
Declare that this class can intercept Controller requests by adding @RestControllerAdvice. Add @ExceptionHandler to the Handle method and specify the exception class to intercept in the annotation.
@RestControllerAdvice // Controller enhancements (return JSON data). Classes with this annotation can be automatically detected by the CLASspath scan
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class) // Catch the specified type of exception thrown by the Controller. You can specify other exceptions as well
public <E>Message<E> handler(Exception exception){
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else {
return MessageUtil.error(120."Exception information:"+ exception.getMessage()); }}}Copy the code
Only custom and unknown exceptions are handled here. If you know explicitly in a method that an exception might be thrown, you can add a specific handler. For example, if you know that a NullPointException may be thrown, you can append the NullPointException handler:
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else if (exception instanceof NullPointException ){
return MessageUtil.error(500."Null pointer exception message!");
} else {
return MessageUtil.error(120."Exception information:" + exception.getMessage());
}
Copy the code
The controller layer
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/{id}")
public Message<Student> findStudentById(@PathVariable("id") Integer id){
if (id < 0) {// Test custom errors
throw new CustomException(110."Parameters cannot be negative numbers!");
} else if (id == 0) {// hardcoded for testing purposes
Integer i = 1/id;
return null;
} else {
Student student = studentService.findStudentById(id);
returnMessageUtil.ok(student); }}}Copy the code
The complete code
https://github.com/turoDog/Demo/tree/master/springboot_exception_demo
If you think it is helpful, please give a Star and then go. Thank you very much.
Postman test
Visit http://localhost:8080/student/5 to test normal return data results.
Visit http://localhost:8080/student/0 to test the unknown abnormal results.
Visit http://localhost:8080/student/-11 to test the result of custom exception.
After the language
If this article is of any help to you, please help to read it. Your good looks are my motivation to keep writing.
In addition, after paying attention to send 1024 can receive free learning materials. Python, C++, Java, Linux, Go, front-end, algorithm sharing