如何拦截 spring aop 方面抛出的异常

How to intercept exception thrown from aspect in spring aop

有什么方法可以拦截异常并向最终客户显示有意义的消息吗?我正在尝试使用 spring AOP 授权我的 api,如果最终用户未被授权访问 API,我将抛出异常。

@Aspect
public class AuthorizationAspect {
  @Pointcut("@annotation(AuthenticateAccount)")
    public void authorized() {}

   private boolean isAuthorized() {
   // logic to check is user is authorised to call the api
   }

    @Before("authorized()")
    public void beforeControllerCall(JoinPoint joinPoint) throws UnauthorizedException {

        if(!isAuthorized)) {
            throw new UnauthorizedException("You don't have rights over this API");
        }

    }
}

通过抛出异常,我可以阻止对 API 的访问,但它不会 return 我试图抛出异常的有意义的消息。

有没有人处理过这样的用例并且可以帮助我解决这个问题?

您可以使用 @ControllerAdvice 使用全局异常处理。创建您的自定义异常并从 Aspect class 中抛出该异常。您可以像这样创建 @ControllerAdvice 带注释的 class:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {UnauthorizedException.class})
    public ResponseEntity<Object> handleException(UnauthorizedException ex){
        return new ResponseEntity<Object>(
      ex.getMessage(), new HttpHeaders(), HttpStatus.FORBIDDEN);
    }

}

编辑:

请在下面找到 spring 引导全局异常处理代码:

DemoController.java

@RestController
public class DemoController {

    @GetMapping("/hello")
    String hello(){
        return "Message from controller if there is no exception";
    }
}

AuthException .java

public class AuthException extends Exception{
    AuthException(String msg){
        super(msg);
    }
}

AopValidator.java

@Aspect
@Component
public class AopValidator {

    @Before("execution(String hello())")
     public void test() throws AuthException{
         throw new AuthException("Exception message from AOP on unauthorized access");
     }
}

GlobalExceptionHandler.java

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AuthException.class)
    ResponseEntity<Object> handleException(AuthException ex){
        return new ResponseEntity<>(ex.getMessage(), new HttpHeaders(), HttpStatus.FORBIDDEN);
    }
}