spring – AOP @Around:返回BAD_REQUEST响应
作者:互联网
在Spring rest应用程序中,每个URL都必须以应用程序ID(appId)开头.必须在每个单独的休息服务中验证此appId.我尝试使用@Around建议创建一个@Aspect,而不是重复代码.这在任何rest方法之前正确执行.
但是,如果应用程序ID未知,我既不想创建堆栈跟踪,也不希望既不返回200(响应OK).相反,我确实想要返回一个BAD_REQUEST响应代码.
如果我在我的建议中抛出一个异常,我得到一个堆栈跟踪而没有HTTP响应.如果我另一方面返回任何其他东西(但不要调用pjp.proceed),我得到的返回码为200.
有人可以帮助我将响应代码400返回给请求者吗?
到目前为止我的代码下面:
@Component
@Aspect
public class RequestMappingInterceptor {
@Autowired
ListOfValuesLookupUtil listOfValuesLookupUtil;
@Around("@annotation(requestMapping)")
public Object around(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {
Object[] arguments = pjp.getArgs();
if(arguments.length == 0 || !listOfValuesLookupUtil.isValidApplication(arguments[0].toString())) {
// toto : return bad request here ...
throw new BadRequestException("Application id unknown!");
} else {
return pjp.proceed();
}
}
}
解决方法:
您可以尝试返回响应实体
if(arguments.length == 0 || !listOfValuesLookupUtil.isValidApplication(arguments[0].toString())) {
return new ResponseEntity<>("Application id unknown!", HttpStatus.BAD_REQUEST);
}else
标签:spring,aop,spring-aop,bad-request 来源: https://codeday.me/bug/20190708/1400029.html