异常处理器:
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,"系统繁忙,请稍后再试!");
}