使用@ControllerAdvice=>aop实现
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandller {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result globalException() {
return Result.fail().message("服务器繁忙请稍后再试");
}
@ExceptionHandler(MyException.class)
@ResponseBody
public Result myException(Exception e) {
return Result.fail().message(e.getMessage());
}
@ExceptionHandler(AccessDeniedException.class) //权限异常
@ResponseBody
public Result error(AccessDeniedException e) {
return Result.fail().code(203).message("没有访问权限");
}
}
其中globalException()方法是全局异常处理,使用@ExceptionHandler()指定细粒度的异常处理 也可以将自定义的异常加入到处理类中
public class MyException extends RuntimeException {
public MyException(String message) {
super(message);
}
}
需要注意: 自定义异常需要手动捕获抛出