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 exceptions in Spring Boot

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to handle exceptions in Spring Boot. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Through this article, you can figure out how to handle exceptions in Spring Boot. However, it is not enough to be able to use it, and we need to think about how to write the exception handling code a little more elegantly. Next, I will talk about the slightly more elegant exception handling solution that I think is a little more elegant in terms of exception handling that I have learned in practical projects.

The following is only from my personal point of view, if readers have a better solution or feel that there is room for optimization, you are welcome to comment in the comments section.

Final effect display

Let's first show the effect after completion. When the defined exception is caught by the system, the information returned to the client is as follows:

Effect display

The returned information contains the following five parts of the exception:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

The code that uniquely marks the exception

HTTP status code

Wrong path

The timestamp in which the error occurred

Error specific information

Returning abnormal information in this way is more beneficial for our front end to make corresponding performance according to abnormal information.

Exception handling core code

ErrorCode.java (this enumeration class contains the unique identity of the exception, the HTTP status code, and the error message)

The main function of this class is to uniformly manage the exceptions that may occur in the system, which is relatively clear. However, the problem that may arise is that when the system is too complex and there are too many exceptions, this class will be large. There is a solution: unify a variety of similar exceptions into one, for example, unify the exceptions that cannot be found by the user and those not found by the order information into the exception of "the resource not found". Then the front end will deal with the corresponding situation in detail (one of my personal handling methods is not guaranteed to be a better one).

Import org.springframework.http.HttpStatus; public enum ErrorCode {RESOURCE_NOT_FOUND (1001, HttpStatus.NOT_FOUND, "resource not found"), REQUEST_VALIDATION_FAILED (1002, HttpStatus.BAD_REQUEST, "request data format verification failed"); private final int code; private final HttpStatus status; private final String message; ErrorCode (int code, HttpStatus status, String message) {this.code = code; this.status = status This.message = message;} public int getCode () {return code;} public HttpStatus getStatus () {return status;} public String getMessage () {return message } @ Override public String toString () {return "ErrorCode {" + "code=" + code + ", status=" + status + ", message='" + message +'\'+'}';}}

ErrorReponse.java (return the specific exception object to the client)

This class is returned to the client as exception information, including all the information we want to return to the client when an exception occurs.

Import org.springframework.util.ObjectUtils; import java.time.Instant; import java.util.HashMap; import java.util.Map; public class ErrorReponse {private int code; private int status; private String message; private String path; private Instant timest private HashMap data = new HashMap () Public ErrorReponse () {} public ErrorReponse (BaseException ex, String path) {this (ex.getError (). GetCode (), ex.getError (). GetStatus (). Value (), ex.getError (). GetMessage (), path, ex.getData ();} public ErrorReponse (int code, int status, String message, String path, Map data) {this.code = code; this.status = status This.message = message; this.path = path; this.timestamp = Instant.now (); if (! ObjectUtils.isEmpty (data)) {this.data.putAll (data) }} / / omit the getter/setter method @ Override public String toString () {return "ErrorReponse {" + "code=" + code + ", status=" + status + ", message='" + message +'\'+ ", path='" + path +'\'+ " Timestamp= "+ timestamp +", data= "+ data +'}' }}

BaseException.java (an abstract class inherited from RuntimeException and can be regarded as the parent of other exception classes in the system)

All exception classes in the system inherit from this class.

Public abstract class BaseException extends RuntimeException {private final ErrorCode error; private final HashMap data = new HashMap (); public BaseException (ErrorCode error, Map data) {super (error.getMessage ()); this.error = error; if (! ObjectUtils.isEmpty (data)) {this.data.putAll (data) }} protected BaseException (ErrorCode error, Map data, Throwable cause) {super (error.getMessage (), cause); this.error = error; if (! ObjectUtils.isEmpty (data)) {this.data.putAll (data);}} public ErrorCode getError () {return error;} public Map getData () {return data }}

ResourceNotFoundException.java (custom exception)

You can see that it is very easy for us to customize exceptions by inheriting the BaseException class!

Import java.util.Map; public class ResourceNotFoundException extends BaseException {public ResourceNotFoundException (Map data) {super (ErrorCode.RESOURCE_NOT_FOUND, data);}}

GlobalExceptionHandler.java (global exception capture)

We define two exception catching methods.

To illustrate again, in fact, all this class needs is the method handleAppException (), because it is the parent of all exceptions in the system. Any exception that inherits the BaseException class will be handled here.

Import com.twuc.webApp.web.ExceptionController; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest @ ControllerAdvice (assignableTypes = {ExceptionController.class}) @ ResponseBody public class GlobalExceptionHandler {/ / you can also change BaseException to RuntimeException / / because RuntimeException is the parent class of BaseException @ ExceptionHandler (BaseException.class) public ResponseEntity handleAppException (BaseException ex, HttpServletRequest request) {ErrorReponse representation = new ErrorReponse (ex, request.getRequestURI ()); return new ResponseEntity (representation, new HttpHeaders (), ex.getError (). GetStatus ()) } @ ExceptionHandler (value = ResourceNotFoundException.class) public ResponseEntity handleResourceNotFoundException (ResourceNotFoundException ex, HttpServletRequest request) {ErrorReponse errorReponse = new ErrorReponse (ex, request.getRequestURI ()); return ResponseEntity.status (HttpStatus.BAD_REQUEST) .body (errorReponse);}}

(important) one extension:

Ha ha! In fact, I added an extra exception catch method, handleResourceNotFoundException (), mainly to test which of the following methods will catch ResourceNotFoundException exceptions when we throw them.

Answer:

Will be captured by the handleResourceNotFoundException () method. Because @ ExceptionHandler will first find the best match in the process of catching an exception.

Here is a brief analysis of the source code:

The getMappedMethod in ExceptionHandlerMethodResolver.java determines which method to handle.

@ Nullable private Method getMappedMethod (Class

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

Development

Wechat

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

12
Report