springBoot配置自定义全局异常捕获

一、方式一

1.配置全局异常捕获类

@RestControllerAdvice(basePackages = {"cn.javasm"})
public class JavasmExceptionAdvice {

    @ExceptionHandler(JavasmException.class)
    public ResponseEntity f1(JavasmException javasmException){
        javasmException.printStackTrace();
        // 当异常产生的时候,触发了此方法
        // 当前方法返回的数据,就是产生异常的时候,返回的数据
        ExceptionEnum exceptionEnum = javasmException.getExceptionEnum();
        return ResponseEntity.ok(exceptionEnum);
    }
}

2.配置自定义异常类

@Getter
public class JavasmException extends RuntimeException {
    private ExceptionEnum exceptionEnum;

    public JavasmException(ExceptionEnum exceptionEnum) {
        super(exceptionEnum.getMsg());
        this.exceptionEnum = exceptionEnum;
    }

}

3.配置自定义异常枚举类

@Getter
@AllArgsConstructor
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ExceptionEnum {

    LoginError(1001,"登陆异常"),
    Parameter_NUll(2001,"参数异常"),
    Goods_Less(5001,"商品数量不足")
    ;

    private Integer code;
    private String msg;
}

4.在service或controller中使用全局自定义异常捕获

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    User user;

    @GetMapping("/query")
    public User query(Integer id) {
        if (id == null) {
            throw new JavasmException(ExceptionEnum.Parameter_NUll);
        }

        return user;
    }
}

二、方式二

1 配置全局异常捕获类

@RestControllerAdvice
public class ProjectExceptionAdvice {

    @ExceptionHandler(SystemException.class) //拦截异常
    public  HashMap<String, Object> doException(SystemException e){
        // 记录日志
        // 发送消息给运维
        // 发送邮件给开发人员

        HashMap<String, Object> map = new HashMap<>();
        map.put("code",e.getCode());
        map.put("msg",e.getMessage());
        map.put("data",null);
        return map;
    }

    @ExceptionHandler(BusinessException.class) //拦截异常
    public  HashMap<String, Object> doException(BusinessException e){
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",e.getCode());
        map.put("msg",e.getMessage());
        map.put("data",null);
        return map;
    }

}

 2 配置自定义异常类

public class BusinessException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public BusinessException(String message, Integer code) {
        super(message);
        this.code = code;
    }

    public BusinessException(String message, Throwable cause, Integer code) {
        super(message, cause);
        this.code = code;
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值