当前位置:   article > 正文

SpringBoot优雅的自定义异常处理_springboot 自定义异常 优雅

springboot 自定义异常 优雅

一、引入pom

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

二、创建异常信息接口

package com.jpxsr.fish.interfaces;

/**
 * 异常信息接口
 * @author 等风来
 * @date 2021年09月09日 10:13
 */
public interface BaseErrorInfoInterface {

    /**
     * 错误码
     * @return
     */
    Integer getCode();

    /**
     * 错误描述
     * @return
     */
    String getMsg();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

三、自定义异常属性枚举

package com.jpxsr.except;


/**
 * @author 等风来
 * @date 2021年09月09日 10:15
 * 异常属性枚举
 */
public enum CodeEnum implements BaseErrorInfoInterface {

    /** 数据操作错误定义 */
    SUCCESS(20000, "成功!"),
    BODY_NOT_MATCH(20001,"请求的数据格式不符!"),
    SIGNATURE_NOT_MATCH(20002,"请求的数字签名不匹配!"),
    NOT_FOUND(404, "未找到该资源!"),
    INTERNAL_SERVER_ERROR(500, "服务器内部错误!"),
    SERVER_BUSY(20003,"服务器正忙,请稍后再试!"),
    KEY_REPEAT(2004, "数据库键值重复!"),
    DIVISOR_ERROR(2005, "0不可以作为除数!");

    /** 错误码 */
    private final Integer code;

    /** 错误描述 */
    private final String msg;

    CodeEnum(Integer resultCode, String resultMsg) {
        this.code = resultCode;
        this.msg = resultMsg;
    }

    @Override
    public Integer getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return msg;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

四、自定义通用返回值

package com.jpxsr.except;


import lombok.Data;
import lombok.experimental.Accessors;


/**
 * @author 等风来
 */
@Accessors(chain = true)
@Data
public class Result {

    /**是否成功*/
    private boolean flag;

    /**返回码*/
    private Integer code;

    /**返回信息*/
    private String message;

    /**返回数据*/
    private Object data;

    private Result() {}

    public Result(BaseErrorInfoInterface errorInfoInterface){
        this.code = errorInfoInterface.getCode();
        this.message = errorInfoInterface.getMsg();
    }

    public static Result SUCCESS() {
        Result result = new Result();
        result.setFlag(true);
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMessage(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    public static Result ERROR(BaseErrorInfoInterface errorInfo) {
        Result result = new Result();
        result.setFlag(false);
        result.setCode(errorInfo.getCode());
        result.setMessage(errorInfo.getMsg());
        return result;
    }

    /**
     * 失败
     */
    public static Result ERROR(Integer code, String message) {
        Result result = new Result();
        result.setFlag(false);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    /**
     * 失败
     */
    public static Result ERROR(String message) {
        Result result = new Result();
        result.setFlag(false);
        result.setCode(-1);
        result.setMessage(message);
        return result;
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

五、自定义异常类

package com.jpxsr.except.exception;

import com.jpxsr.except.BaseErrorInfoInterface;
import lombok.Getter;
import lombok.Setter;

/**
 * @author 等风来
 * @date 2021年09月09日 10:17
 * 自定义异常
 */
@Getter
@Setter
public class MyException extends RuntimeException{
    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     */
    private Integer errorCode;
    /**
     * 错误信息
     */
    private String errorMsg;

    public MyException() {
        super();
    }

    public MyException(String errorMsg) {
        super(errorMsg);
        this.errorMsg = errorMsg;
    }

    public MyException(BaseErrorInfoInterface errorInfoInterface) {
        super(errorInfoInterface.getMsg());
        this.errorCode = errorInfoInterface.getCode();
        this.errorMsg = errorInfoInterface.getMsg();
    }

    public MyException(Integer errorCode, String errorMsg) {
        super(errorMsg);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public MyException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) {
        super(errorInfoInterface.getMsg(), cause);
        this.errorCode = errorInfoInterface.getCode();
        this.errorMsg = errorInfoInterface.getMsg();
    }


    public MyException(Integer errorCode, String errorMsg, Throwable cause) {
        super(errorMsg, cause);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    @Override
    public Throwable fillInStackTrace() {
        return this;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65

六、配置全局异常处理

这里可以自定义很多异常处理

package com.jpxsr.except.exception;


import com.jpxsr.except.CodeEnum;
import com.jpxsr.except.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 等风来
 * @date 2021年09月09日 10:19
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, MyException e){
        logger.error("发生业务异常!原因是:{}",e.getErrorMsg());
        return Result.ERROR(e.getErrorCode(),e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, NullPointerException e){
        logger.error("发生空指针异常!原因是:",e);
        return Result.ERROR(CodeEnum.BODY_NOT_MATCH);
    }

    /**
     * 处理数据库唯一键重复的异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = DuplicateKeyException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, DuplicateKeyException e){
        logger.error("发生键值重复异常!原因是:",e);
        return Result.ERROR(CodeEnum.KEY_REPEAT);
    }


    /**
     * 处理数据库唯一键重复的异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = ArithmeticException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, ArithmeticException e){
        logger.error("除零异常!原因是:",e);
        return Result.ERROR(CodeEnum.DIVISOR_ERROR);
    }


    /**
     * 处理其他异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, Exception e){
        logger.error("未知异常!原因是:",e);
        return Result.ERROR(CodeEnum.INTERNAL_SERVER_ERROR);
    }
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92

七、测试

package com.jpxsr.except;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 等风来
 * @date 2021年09月22日 15:54
 */
@RestController
public class TextController {

    @GetMapping("/text")
    public float text(){
        float a = 0;
        a = 1/0;
        return a;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

访问路径:localhost:8080/text, 出现一下异常提示信息。

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/二进制舞者/article/detail/62647
推荐阅读
相关标签
  

闽ICP备14008679号