[SpringBoot topic] Unified exception handling and unified data return

In actual development, we hope to carry out a unified encapsulation of the interface result return, even if the interface is abnormal. For example, we can design the return of the interface like this:

Unified data return

We hope that there is a unified way to handle exceptions, and there is a unified way to return interface results, and write as little code as possible, and separate it from the processing of business logic as much as possible.

 

practice

Step 1: Define a common data return object

GlobalResponse

Here we define a general data return object and provide a quick setting method for normal data return/an abnormal data return.

Step 2: Define a unified processing handler

GlobalResponseHandler

@ControllerAdvice+@ExceptionHandler used in conjunction

First, we define a controller enhanced processor through @ControllerAdvice, which can be used in conjunction with @ExceptionHandler for unified exception handling.

Second, by implementing ResponseBodyAdvice, further processing is performed on the return of the data, so that the return value of the interface is a unified object.

Business exception

 

operation result

The interface returns normally

The data returned normally is packaged uniformly

Interface exception

Abnormal return

 

Well, here, we have an understanding of exception handling and unified interface data return in springboot~

 

Guess you like

Origin blog.csdn.net/yunduo1/article/details/108681656