Unified (global, special, custom) exception handling of spring boot project

Keywords: Java Programming

I. application scenarios

   when there is an error in the program, we do not want the page to directly return "404", "500" and other information. In order to improve the user experience, we need to handle exceptions uniformly and give friendly prompts!

II. Anomaly classification

   (1) unified exception handling: it is recommended to return a unified result as long as an exception occurs.

   (2) special exception handling: generally not used because the exception of the project cannot be accurately located.

   (3) user defined exception handling: create an exception by yourself and return the result. You need to call (try...catch) manually to execute!

III. implementation code

                     .

Note: the priority of special exception handling is higher than that of unified exception handling! </font>

/**
 * @BelongProjecet: guli-framework-parent
 * @BelongPackage: com.guliedu.eduservice.handler
 * @ClassName: GlobalExceptionHandler
 * @Description: [Recommended > method 1] unified exception handling: as long as an exception occurs, a unified result will be returned
 *               [Method 2] special exception handling: if there is an ArithmeticException exception, it will be handled.
 *                          Special exception handling > unified exception handling (priority)
 *               [Recommended > method 3] user defined exception handling: create an exception by yourself and return the result by yourself
 * @Copyright: 2019-xxx-Powered by R & D four
 * @Author: LinHong
 * @CreateDate: 2019/11/13 20:42
 * @Version: V1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * Function description
     *
     * @MethodName:
     * @MethodParam:
     * @Return:
     * @Description: How to deal with global exception
     * @Author: LinHong
     * @CreateDate: 2019/11/13 20:47
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        e.printStackTrace();
        return R.error().message("Global exception handling method executed......");

    }

    /**
     * Function description
     *
     * @MethodName: error
     * @MethodParam: [e]
     * @Return: com.guliedu.common.R
     * @Description: Methods of handling special exceptions
     * @Author: LinHong
     * @CreateDate: 2019/11/13 20:52
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public R error(ArithmeticException e) {
        e.printStackTrace();
        return R.error().message("Special exception handling method executed......");

    }
    /**
     * Function description
     * @MethodName: error
     * @MethodParam: [e]
     * @Return: com.guliedu.common.R
     * @Description: Custom exception - exception needs to be thrown manually!!!
     * @Author: LinHong
     * @CreateDate: 2019/11/14 10:05
     */
    @ExceptionHandler(EduException.class)
    @ResponseBody
    public R error(EduException e) {
       // EduException e1 = new EduException(20001, "user defined exception test, operation failed...";
        e.printStackTrace();
        return R.error().code(e.getCode()).message(e.getMsg());

    }

}

EduException custom exception class

Inherit the runtime exception class and add two properties: status code and return information.

/**
 * @BelongProjecet: guli-framework-parent
 * @BelongPackage: com.guliedu.eduservice.handler
 * @ClassName: EduException
 * @Description: Custom exception
 * @Copyright: 2019-xxx-Powered by R & D four
 * @Author: LinHong
 * @CreateDate: 2019/11/14 9:58
 * @Version: V1.0
 */
@Data
//Non parametric structure
@NoArgsConstructor
//Parametric structure
@AllArgsConstructor
public class EduException extends RuntimeException{
    //Status code
    private Integer code;
    //Return information
    private String msg;

}

(custom exception test) exception location

Note: user defined Exceptions need to be called manually before execution!

    /**
         *Test special exception
         */
        try {
            int i =666/0;
        } catch (Exception e) {
            //Throw custom exception
            throw new EduException(20001,"Custom exception test, do this.......");
        }

R return result class (attached)

/**
 * @BelongProjecet: guli-framework-parent
 * @BelongPackage: com.guliedu.common
 * @ClassName: R
 * @Description: Return result class -- chain programming
 * @Copyright: 2019-xxx-Powered by R & D four
 * @Author: LinHong
 * @CreateDate: 2019/11/13 14:32
 * @Version: V1.0
 */
@Data
public class R {
    private boolean success;
    private Integer code;
    private String message;
    private Map<String, Object> data = new HashMap<>();
    //Constructor privatization
    private R(){}
    //Provide accessible methods externally
    public static R ok(){
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.OK);
        r.setMessage("Success");
        return r;
    }

    public static R error(){
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("fail");
        return r;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value){
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map){
        this.setData(map);
        return this;
    }
}

ResultCode data status code interface (attached)

package com.guliedu.common;

/**
 * @BelongProjecet: guli-framework-parent
 * @BelongPackage: com.guliedu.common
 * @ClassName: ResultCode
 * @Description: Write unified result return, create common module -- define return data status code
 * @Copyright: 2019-xxx-Powered by R & D four
 * @Author: LinHong
 * @CreateDate: 2019/11/13 14:20
 * @Version: V1.0
 */
public interface ResultCode {
    //Success
    int OK = 20000;
    //fail
    int ERROR =20001;
    //Wrong user name or password
    int LOGIN_ERROR =20002;
    //Insufficient authority
    int ACCEAA_ERRORR=20003;
    //Remote call failed
    int REMOTE_ERROR = 20004;
    //Repetitive operation
    int REPEAT_ERROR = 20005;
}

♚ learn, practice, summarize and share to make life better!
☞ great Xia Lin CSDN blog: https://coding0110lin.blog.csdn.net/ Welcome to reprint and discuss with us!

Posted by happyness on Wed, 20 Nov 2019 09:16:05 -0800