全局和特定
package com.atguigu.common.config.exception;
import com.atguigu.common.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 全局异常处理类
*
*/
@ControllerAdvice
public class GlobalExceptionHandler {
//出现那种异常时执行
@ExceptionHandler(Exception.class)
//返回json数据所需要的,为了能返回json数据
@ResponseBody
public Result error(Exception e){
e.printStackTrace();
return Result.fail().message("执行全局异常处理....");
}
//特定异常处理
//出现那种异常时执行
@ExceptionHandler(ArithmeticException.class)
//返回json数据所需要的,为了能返回json数据
@ResponseBody
public Result error(ArithmeticException e){
e.printStackTrace();
return Result.fail().message("执行特定异常处理....");
}
}
自定义异常处理
1 创建异常类,继承RuntimeExceeption
package com.atguigu.common.config.exception;
import com.atguigu.common.result.ResultCodeEnum;
import lombok.Data;
@Data
public class GuiguException extends RuntimeException {
private Integer code;
private String msg;
public GuiguException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
/**
* 接收枚举类型对象
* @param resultCodeEnum
*/
public GuiguException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
this.msg = resultCodeEnum.getMessage();
}
@Override
public String toString() {
return "GuliException{" +
"code=" + code +
", message=" + this.getMessage() +
'}';
}
}
2 手动抛出异常
//模拟异常效果
try {
int i=10/0;
} catch (Exception e){
//手动抛出自定义异常
throw new GuiguException(2001,"处理了自定义异常!");
}
3 添加执行方法
//自定义异常处理
//出现那种异常时执行
@ExceptionHandler(GuiguException.class)
//返回json数据所需要的,为了能返回json数据
@ResponseBody
public Result error(GuiguException e){
e.printStackTrace();
return Result.fail().code(e.getCode()).message(e.getMsg());
}