Spring boot exception handling unified encapsulation

Posted by neomhm on Sat, 02 Nov 2019 16:58:13 +0100

brief introduction

I'll write the repetition function. In the spring boot project, there are global exception handling and return packaging. The return front end is to bring fields such as succ, code, msg and data. It's easy to solve in the case of a single project. When there are many micro service modules, in many cases, the development is to copy the original code to build another project, which leads to the need to modify multiple services in order to upgrade these functions. On this basis, we encapsulate a component, unified dispose SpringBoot starter, which contains some basic exception handling and return packaging functions Yes.

Dependency add start function

Add dependency
ps: please use the latest version for the actual version
Latest version:

Click to view the latest version

<dependency>
  <groupId>com.purgeteam</groupId>
  <artifactId>unified-dispose-springboot-starter</artifactId>
  <version>0.1.1.RELEASE</version>
</dependency>

The startup class adds the @ EnableGlobalDispose annotation to enable the following functions.

@EnableGlobalDispose
@SpringBootApplication
public class GlobalDisposeSpringBootApplication {

  public static void main(String[] args) {
    SpringApplication.run(GlobalDisposeSpringBootApplication.class, args);
  }

}

One exception handling

System exceptions often occur in projects, such as NullPointerException and so on. If it is not handled by default, springboot will respond to the default error prompt, so it is not friendly to the user experience. System level errors cannot be perceived by the user. Even if the error is 500, it can give the user a friendly prompt similar to the server error.

The module also contains some basic exception handling methods (and basic exception handling without any code writing), as well as some common exception codes. Users only need to care about the business exception handling and directly throw it through throw new exception.

Exception handling contains types

#General 500 exception
 Exception class catches 500 exception handling

#Feign exception
 FeignException class capture
 ClientException class capture

#Business customization
 BusinessException class catches business common custom exception

#Parameter verification exception
 HttpMessageNotReadableException parameter error exception
 BindException parameter error exception

The program actively throws an exception

throw new BusinessException(BusinessErrorCode.BUSINESS_ERROR);
// perhaps
throw new BusinessException("CLOUD800","No excess inventory");

In general, it is not recommended to throw a general BusinessException exception exception directly. You should add the exception handling class of the corresponding domain and the corresponding enumeration error type in the corresponding module.

For example, member module:
Create UserException exception exception class, UserErrorCode enumeration, and UserExceptionHandler unified interception class.

UserException:

@Data
public class UserException extends RuntimeException {

  private String code;
  private boolean isShowMsg = true;

  /**
   * Using enumeration parameters
   *
   * @param errorCode Exception enumeration
   */
  public UserException(UserErrorCode errorCode) {
    super(errorCode.getMessage());
    this.setCode(errorCode.getCode());
  }

}

UserErrorCode:

@Getter
public enum UserErrorCode {
    /**
     * Permission exception
     */
    NOT_PERMISSIONS("CLOUD401","You do not have permission to operate"),
    ;

    private String code;

    private String message;

    CommonErrorCode(String code, String message) {
        this.code = code;
        this.message = message;
    }
}

UserExceptionHandler:

@Slf4j
@RestControllerAdvice
public class UserExceptionHandler {

  /**
   * UserException Class capture
   */
  @ExceptionHandler(value = UserException.class)
  public Result handler(UserException e) {
    log.error(e.getMessage(), e);
    return Result.ofFail(e.getCode(), e.getMessage());
  }

}

The final business use is as follows:

// Determine if you have permission to throw an exception
throw new UserException(UserErrorCode.NOT_PERMISSIONS);

In the above way, exceptions will be thrown and processed by the module. The front desk returns as follows:

{
  "succ": false,        // Success
  "ts": 1566467628851,  // time stamp
  "data": null,         // data
  "code": "CLOUD800",   // Error type
  "msg": "Business exception",    // Wrong description
  "fail": true
}

How unified return seal

In REST style development, avoid telling the foreground whether the return is successful and the status code. Here, we usually do a package processing of util when we return. For example, a class like Result contains fields such as succ, code, msg and data.

The interface call processing is similar to the following:

  @GetMapping("hello")
  public Result list(){
    return Result.ofSuccess("hello");
  }

Result:

{
  "succ": ture,         // Success
  "ts": 1566467628851,  // time stamp
  "data": "hello",      // data
  "code": null,         // Error type
  "msg": null,          // Wrong description
  "fail": true
}

Function use

By default, all web controller s are encapsulated in the following return format.

Interface:

@GetMapping("test")
public String test(){
  return "test";
}

Return

{
  "succ": true,             // Success
  "ts": 1566386951005,      // time stamp
  "data": "test",           // data
  "code": null,             // Error type
  "msg": null,              // Wrong description
  "fail": false             
}

Ignore encapsulation comment: @ ignorereconseadvice

@The allowed range of ignorereponseadvice is: class + method. The return of the said method under the class marked on the class will ignore the return encapsulation.

Interface:

@Ignorereconseadvice / / ignore data wrappers to add to classes and methods
@GetMapping("test")
public String test(){
  return "test";
}

Return to test

summary

There are many duplicate code s in the project. We can simplify them in a certain way to achieve a certain goal and reduce the amount of development. The purge team has some excellent open source components to reduce the daily development volume.

Example code address: unified-dispose-springboot

By GitHub:
Purgeyao Welcome to your attention.

qq communication group: 812321371 wechat communication group: mercy Yao

WeChat public address:

Topics: Java SpringBoot Spring REST github