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>

二、创建异常信息接口

package com.jpxsr.fish.interfaces;

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

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

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

三、自定义异常属性枚举

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;
    }
}

四、自定义通用返回值

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;
    }

}

五、自定义异常类

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;
    }
}

六、配置全局异常处理

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

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);
    }
}


七、测试

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;
    }
}

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

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EOPG

你的鼓励是我创造的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值