SSM整合(四)---异常处理器

异常处理器:

在这里插入图片描述

1.所有的异常都抛到表现层进行处理
2.表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,因此采用AOP思想来处理异常
3.Spring提供了异常处理器,来集中的、统一的处理项目中出现的异常。

在controller包下创建异常处理器ProjectExceptionAdvice:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

项目异常处理

在这里插入图片描述
在这里插入图片描述

1.自定义项目异常

在这里插入图片描述

a.自定义项目系统级异常SystemException
package com.itheima.exception;

public class SystemException extends RuntimeException{
    //异常编号
    private Integer code;

    public SystemException(Integer code) {
        this.code = code;
    }

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

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

    public Integer getCode() {
        return code;
    }

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

b.自定义项目业务级异常BussinessException
package com.itheima.exception;

public class BussinessException extends RuntimeException {
    private Integer code;

    public BussinessException(Integer code) {
        this.code = code;
    }

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

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

    public Integer getCode() {
        return code;
    }

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

2.定义异常代码

在这里插入图片描述

3.出现异常

下面模拟出现异常的情况:
在这里插入图片描述

4.在ProjectExceptionAdvice中根据不同类型的异常创建不同的异常处理器

a.处理系统异常
//用来处理系统异常
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException e)
    {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员(包括异常对象)
        return new Result(e.getCode(),null,e.getMessage());
    }
b.处理业务异常
//处理业务异常
    @ExceptionHandler(BussinessException.class)
    public Result doBussinessException(BussinessException e)
    {
        return new Result(e.getCode(),null,e.getMessage());
    }

c.处理其他异常
//处理其它异常
    @ExceptionHandler(Exception.class)
    public Result doException(Exception e)
    {
        System.out.println(e);
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值