统一异常处理
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)//当出现什么异常会执行以下方法
@ResponseBody//返回数据
public Result error(Exception e){
e.printStackTrace();
return Result.error().message("异常,请联系admin");
}
@ExceptionHandler(ArithmeticException.class)//当出现什么异常会执行以下方法
@ResponseBody//返回数据
public Result error(ArithmeticException e){
e.printStackTrace();
return Result.error().message(e.getMessage());
}
@ExceptionHandler(MyException.class)//当出现什么异常会执行以下方法
@ResponseBody//返回数据
public Result error(MyException e){
e.printStackTrace();
return Result.error().code(e.getCode()).message(e.getMessage());
}
}