Full project address: Micro-service-plus

Series entry:

  • Take you to the background with SpringCloud micro-service (entrance)

preface

This section describes how @RestControllerAdvice catches global exceptions and returns them to the front end

We mainly use ty-example as an example to illustrate

Note: Micro-services in Micro-service-Plus reference configurations and dependencies in TY-Common

Introduction to core Files

ty-common/khcomomon/exception/BaseExceptionHandler

/* * Global exception handling * */
// @restControllerAdvice catches errors in the current micro-service and returns the error information to the front end
@RestControllerAdvice
public class BaseExceptionHandler {
    // If there is a problem with the passed method or parameter, return directly to the front end
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return  new ResResult().error(objectError.getDefaultMessage());
    }
    // Microservice Exception monitor. If Exception related exceptions (including RunTimeException) are generated in microservice, return directly to the front end
    @ExceptionHandler(value = Exception.class)
    public ResResult error(Exception e) {
        e.printStackTrace();
        return newResResult().error(e.getMessage()); }}Copy the code

Config /BaseConfig in ty-example

/* * Summary: @ComponentScan at 1.@Configuration will scan the package with @Component as a configuration class, while @springBootApplication will scan the package as a normal class
@Configuration
@ComponentScan(basePackages = {"top.kuanghua.khcomomon"})
//mapper scanning
@MapperScan(basePackages = {"top.kuanghua.tyexample.mapper"})
//feign scanning
@EnableFeignClients(basePackages = {"top.kuanghua.feign"})
public class BaseConfig {}Copy the code

@ComponentScan(basePackages = {“top.kuanghua.khcomomon”})

The configuration under TY-common/Khcomomon will be changed

Scan all of them, including BaseExceptionHandler, mybitsPlusConfig, Swagger, etc

Note: There are BaseConfig files in each microservice for general basic configuration, including BaseExceptionHandler, mybitsPlusConfig, Swagger basic configuration, etc

Now that you have imported BaseExceptionHandler into your project, how can you use it more elegantly?

Let’s look at a piece of code

ty-example/service/UploadService

        // Check the contents of the file
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        if (bufferedImage == null) {
            log.info("File cannot be empty: {}", originalFilename);
            throw new RuntimeException("File cannot be empty.");
        }
Copy the code

Throw new RuntimeException(” File contents are illegal “); This code is written in the Service, but the BaseExceptionHandler will do the catching directly back to the front end, without the Controller layer handling it itself. So throw new RuntimeException if you want to go back and tell the front end. It saves a lot of work

Experience the address

The front-end receives the following:

{flag: false, code: 20001, msg: "File cannot be empty.", data: null}
Copy the code

So you don’t have to write too much error handling logic in the service, and you don’t have to write the code logic that returns the front end, just throw new RuntimeException(” file can’t be empty “), and that’s it

The generic return class ResResult

ty-common\src\main\java\top\kuanghua\khcomomon\entity\ResResult.java

@Data
@AllArgsConstructor
public class ResResult<T> implements Serializable {
    private static final long serialVersionUID = 2344775856369318037L;
    private boolean flag;// Check whether it succeeds
    private Integer code;/ / return code
    private String msg;// Returns a message
    private T data;// Return data

    // Success returns passable data
    public ResResult success(Object data) {
        this.flag = true;
        this.code = StatusCode.OK;
        this.data = (T) data;
        return this;
    }
    // Successful return
    public ResResult success(a) {
        this.flag = true;
        this.code = StatusCode.OK;
        this.msg = "Operation successful!";
        return this;
    }
    // Failure returns can be passed in MSG
    public ResResult error(String msg) {
        this.flag = false;
        this.code = StatusCode.ERROR;
        this.msg = msg;
        return this;
    }
   MSG and data can be passed in on failure
    public ResResult(String msg, Object data) {
        this.flag = true;
        this.code = StatusCode.OK;
        this.msg = msg;
        this.data = (T) data;
    }

    public ResResult(boolean flag, Integer code, String msg) {
        this.flag = flag;
        this.code = code;
        this.msg = msg;
    }

    public ResResult(a) {
        this.flag = true;
        this.code = StatusCode.OK;
        this.msg = "Operation successful!"; }}Copy the code

How to use

/ / success
@GetMapping("sendEmailText")
public ResResult sendEmailText(a) {
  return new ResResult().success("Email sent successfully");
}
/ / fail
return new ResResult().error(e.getMessage());
Copy the code