spring-boot-route (four) global exception handling

In development, we often use try/catch块to catch exceptions for processing. If some codes forget to catch exceptions or some invisible exceptions appear, they will respond to some unfriendly prompts to the front end. At this time, we can use global exception handling. In this way, there is no need to write those annoying things in the try/catch块了code, and the readability of the code will be improved.

The annotations provided by SpringBoot @ControllerAdviceindicate that global exception capture is enabled and used on custom exception methods ExceptionHandlerfor unified processing.

Let's take a look at how to handle global exceptions gracefully!

An enumeration class that defines response status codes and information

@Getter
public enum CodeEnum {

    SUCCESS(0,"请求成功"),
    ERROR(500,"未知异常"),
    ERROR_EMPTY_RESULT(1001,"查询结果为空"),
    ERROR_INCOMPLETE_RESULT(1002,"请求参数不全");

    private int code;
    private String message;
    CodeEnum(int code,String message){
        this.code = code;
        this.message = message;
    }
}

Two define the entity class of the response data

@Slf4j
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 572235155491705152L;
    /**
     * 响应的状态码
     */
    private int code;
    /***
     * 响应的信息
     */
    private String message;
    /**
     * 响应数据
     */
    private T data;

    /**
     * 放入响应码并返回
     * @param code
     * @param msg
     * @return
     */
    public R fillCode(int code,String msg){
        this.code = code;
        this.message = msg;
        return this;
    }

    /**
     * 放入响应码并返回
     * @param codeEnum
     * @return
     */
    public R fillCode(CodeEnum codeEnum){
        this.code = codeEnum.getCode();
        this.message = codeEnum.getMessage();
        return this;
    }

    /**
     * 放入数据并响应成功状态
     * @param data
     * @return
     */
    public R fillData(T data){
        this.code = CodeEnum.SUCCESS.getCode();
        this.message = CodeEnum.SUCCESS.getMessage();
        this.data = data;
        return this;
    }
}

Three custom two exceptions

Customize exceptions based on business needs. In this article, I defined two exceptions, which are used to handle when the response result is empty and when the request parameter is wrong.

@Data
public class EmptyResutlException extends RuntimeException {

    private static final long serialVersionUID = -8839210969758687047L;
    private int code;
    private String message;

    public EmptyResutlException(CodeEnum codeEnum){
        this.code = codeEnum.getCode();
        this.message = codeEnum.getMessage();
    }
}
@Data
public class RequestParamException extends RuntimeException {

    private static final long serialVersionUID = 4748844811214637041L;
    private int code;
    private String message;

    public RequestParamException(CodeEnum codeEnum){
        this.code = codeEnum.getCode();
        this.message = codeEnum.getMessage();
    }
}

Four define the global exception handling class

Because here I want to respond to the results for the entity class object, so I directly @RestControllerAdviceinstead of @ControllerAdvice, annotated with the difference between the two @Controllerand @RestController, like rest of the body in response to data json format.

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 查询结果为空时处理
     * @param e
     * @return
     */
    @ExceptionHandler(EmptyResutlException.class)
    public R emptyResultExceptionHandler(EmptyResutlException e){
        log.error("查询结果为空:{}",e.getMessage());
        R result = new R();
        result.fillCode(e.getCode(),e.getMessage());
        return result;
    }

    /**
     * 请求参数错误时处理
     * @param e
     * @return
     */
    @ExceptionHandler(RequestParamException.class)
    public R requestParamExceptionHandler(RequestParamException e){
        log.error("请求参数不合法:{}",e.getMessage());
        R result = new R();
        result.fillCode(e.getCode(),e.getMessage());
        return result;
    }

    /**
     * 处理其他异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e){
        log.error("未知异常:{}",e.getMessage());
        R result = new R();
        result.fillCode(CodeEnum.ERROR);
        return result;
    }
}

Five custom interface test exception

@RestController
public class TestController {

    @GetMapping("getString")
    public R getString(String name){

        if(StringUtils.isEmpty(name)){
            throw new RequestParamException(1002,"请求参数name为空");
        }else if ("Java旅途".equals(name)) {
            // 这里没有查询操作,当请求参数是Java旅途的时候,模拟成查询结果为空
            throw new EmptyResutlException(1001,"查询结果为空");
        }
        // 这里模拟一下除自定义异常外的其他两种异常
        int i = 0;
        i = 5/i;
        return new R().fillData(name);
    }
}

In actual development, you can customize the enumeration classes and custom exceptions that respond to status codes to meet your needs.

This is the fourth article in the spring-boot-route series. The articles in this series are relatively simple. The main purpose is to help students who are new to Spring Boot have a systematic understanding. This article has been included in my github , welcome friends star!

githubhttps://github.com/binzh303/spring-boot-route

Pay attention, don't get lost

If you feel good essays, welcome attention , thumbs up , collection , your support is my creative power, thank you.

If there is a problem with the writing of the article, please don't be stingy. Please leave a message and point it out. I will check and modify it in time.

If you want to know me more deeply, you can search for " Java Journey " on WeChat to follow. Reply " 1024 " to get learning videos and exquisite e-books. Push technical articles on time at 7:30 every day, so that you are not alone on your way to work, and there are monthly book delivery activities to help you improve your hard power!

Guess you like

Origin blog.51cto.com/14820531/2539994