【SpringBoot】处理全局异常(附源码)

该博客围绕Spring Boot展开异常处理相关内容。介绍了自定义业务异常、错误码枚举、统一返回格式的Result及全局异常处理器,还给出了源码链接并进行测试,展示了测试结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码

自定义一个业务异常

@Data
public class DemoException extends RuntimeException{

    private static final long serialVersionUID = 1L;

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

    public DemoException() {}

    public DemoException(ResultEnum resultEnum){
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }
}

错误码枚举

public enum ResultEnum {

    UNKONW_ERROR(-1,"未知错误"),
    SUCCESS(0,"成功"),

    ERROR(10001,"自定义业务异常信息"),
    ;

    private Integer code;
    private String msg;

    ResultEnum(Integer code,String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public static String getMsg(int code) {
        for (ResultEnum ele : values()) {
            if(ele.getCode().equals(code)) return ele.getMsg();
        }
        return null;
    }
}

统一返回格式的Result

@Data
public class Result {

    private int code;

    private int count = 0;

    private String msg;

    private Object data;

}

全局异常处理器

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = DemoException.class)
    public ResponseEntity<?> handlerException(HttpServletRequest request, CustomerException e) {
        Result error = new Result();
        // 业务异常
        if(e instanceof DemoException) {
            log.info(this.getClass() + "业务异常:{}", e.getMessage());
            error.setCode(e.getCode());
            error.setMsg(e.getMessage());
//            error.setData(new JsonObject());
            return new ResponseEntity<>(error, HttpStatus.OK);
        }
        // 未知错误
        error.setCode(ResultEnum.UNKONW_ERROR.getCode());
        error.setMsg(ResultEnum.UNKONW_ERROR.getMsg());
        return new ResponseEntity<>(error, HttpStatus.OK);
    }
}

测试一下

@RestController
@RequestMapping("test")
public class TestContrller {
    @GetMapping("/testError")
    public Result testError() throws DemoException {
        throw new DemoException(ResultEnum.ERROR);
    }
}
  • 测试结果
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值