文章目录
1. spring当中异常的处理方式
spring当中异常的处理方式有三种:
1)全局异常处理方法
2)特定异常处理方法
3)通过自定义的方法去处理异常
1.1.全局异常处理方法
//这里的名字GlobalExceptionHandler 是自己起的
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常 @ExceptionHandler(Exception.class)通过异常处理器然后去获取异常
* @param e 异常
* @return 返回值
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e){
e.printStackTrace();
return Result.fail();
}
}
1.2.特定异常处理方法
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常 @ExceptionHandler(Exception.class)通过异常处理器然后去获取异常
* @param e 异常
* @return 返回值
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e){
e.printStackTrace();
return Result.fail();
}
/**
*特殊异常处理 @ExceptionHandler(ArithmeticException.class) 对ArithmeticException异常的处理
* @param e 异常
* @return 返回值
*/
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public Result error(ArithmeticException e){
e.printStackTrace();
return Result.fail().message("执行了特定异常处理");
}
}
1.3.
1)定义异常类
package com.atguigu.common.config.exception;
import com.atguigu.common.result.ResultCodeEnum;
import lombok.Data;
//自定义的异常都需要去继承RuntimeException
@Data
public class GuiguException extends RuntimeException{
private Integer code;
private String message;
/**
* 通过状态码和错误信息创建异常信息
* @param code 状态码
* @param message 异常信息
*/
public GuiguException(Integer code,String message){
super(message);
this.code = code;
this.message = message;
}
/**
* 通过枚举类处理异常信息
* @param resultCodeEnum 枚举类
*/
public GuiguException(ResultCodeEnum resultCodeEnum){
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
this.message = resultCodeEnum.getMessage();
}
@Override
public String toString() {
return "GuiguException{" +
"code=" + code +
", message='" + message + '\'' +
'}';
}
}
2)在GlobalExceptionHandler 类里面声明我们自定义的异常
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常 @ExceptionHandler(Exception.class)通过异常处理器然后去获取异常
* @param e 异常
* @return 返回值
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e){
e.printStackTrace();
return Result.fail();
}
/**
*特殊异常处理 @ExceptionHandler(ArithmeticException.class) 对ArithmeticException异常的处理
* @param e 异常
* @return 返回值
*/
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public Result error(ArithmeticException e){
e.printStackTrace();
return Result.fail().message("执行了特定异常处理");
}
/**
* 自定义异常方式 @ExceptionHandler(GuiguException.class) 对自定义GuiguException异常的处理
* @param e 异常
* @return 返回值
*/
@ExceptionHandler(GuiguException.class)
@ResponseBody
public Result error(GuiguException e){
e.printStackTrace();
return Result.fail().message(e.getMessage()).code(e.getCode());
}
}
1.4 总结
上面说的 全局异常处理方法、特定异常处理方法、通过自定义的方法去处理异常的优先级:
通过自定义的方法去处理异常>特定异常处理方法>全局异常处理方法