如何在春季 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 的访问,但它不会返回我试图抛出异常的有意义的消息。

有没有人使用过这样的用例,可以帮助我解决这个问题?

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

@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 引导全局异常处理代码:

演示控制器.java

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

身份验证异常.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");
}
}

全局异常处理程序.java

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

最新更新