Spring boot 七 全局异常处理

Spring boot 全局异常捕获非常简单。

非常简单
@ControllerAdvice Controller增强 会拦截Controller中的 你配置的事件。
那些事件呢??
在工程中通常会配置一些 自己抛出的异常 或者 系统抛出的异常

//捕获所有Exception 异常
@ExceptionHandler(Exception.class)
//捕获MyException异常 MyException 就是你自己定义的
@ExceptionHandler(MyException.class)
//捕获MyException异常 BusinessException 也是自己定义的这样你就可以分别处理了
@ExceptionHandler(BusinessException.class)

关于自定义的异常可以继承 RuntimeException

public class BusinessException  extends RuntimeException {
    private Integer code;
    private String errorMessage;

    public ServiceException(Integer code, String errorMessage) {
        super(errorMessage);
        this.code = code;
        this.errorMessage = errorMessage;
    }

    public ServiceException(AbstractBaseExceptionEnum exception) {
        super(exception.getMessage());
        this.code = exception.getCode();
        this.errorMessage = exception.getMessage();
    }

    public Integer getCode() {
        return this.code;
    }

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

    public String getErrorMessage() {
        return this.errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

//下面是关机代码,

@ControllerAdvice
public class ControllerLog {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(NoUserException.class)
    @ResponseStatus(HttpStatus.OK) //返回状态码 设置 ok 就是 200
    public String handleException(NoUserException e, Model model) {
        //比如 捕获 MyException 我想存数据库
        model.addAttribute("tips","没有该用户");
        return "/login.html";
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody //如果要返回json 需要使用该注解
    public Error handleException(BusinessException e) {
        //比如 捕获 BusinessException 我正常返回,但是告诉客服输入错误
        log.error("业务日志异常", e);
        return new Error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleException(Exception e) {
        log.error("服务器异常", e);
        return "/error.html";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值