AOP @Around:返回 BAD_REQUEST 响应 [英] AOP @Around: return BAD_REQUEST response
问题描述
在 Spring rest 应用程序中,每个 URL 都必须以应用程序 ID (appId) 开头.此 appId 必须在每个休息服务中进行验证.我没有复制代码,而是尝试使用 @Around 建议创建一个 @Aspect.这是在任何 rest 方法之前正确执行的.
In a Spring rest application, every single URL must start with an application id (appId). This appId must be validated in every single rest service. Instead of duplicating code, I tried to create an @Aspect with an @Around advice. This is correctly executed before any rest method.
但是,如果应用程序 ID 未知,我既不想创建堆栈跟踪,也不想返回 200(响应 OK).相反,我确实想返回 BAD_REQUEST 响应代码.
However, if the application id is unknown, I do not want neither to create a stack trace or neither to return a 200 (response OK). Instead I do want to return a BAD_REQUEST response code.
如果我在建议中抛出异常,我会得到堆栈跟踪,但没有 HTTP 响应.另一方面,如果我返回任何其他内容(但不调用 pjp.proceed),我会得到 200 的返回代码.
If I throw an exception in my advice, I get a stack trace and no HTTP response. If I on the other hand return anything else (but do not call the pjp.proceed), I get a return code of 200.
有人可以帮助我将响应代码 400 返回给请求者吗?
Could anyone please assist me on returning a response code 400 to the requestor?
在我的代码下面:
@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();
}
}
}
推荐答案
您需要访问 HttpServletResponse
并使用它来发送错误代码.您可以通过 RequestContextHolder
You need to access the HttpServletResponse
and use that to send the error code. You can do this via the RequestContextHolder
@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())) {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse());
response.sendError(HttpStatus.PRECONDITION_FAILED.value(), "Application Id Unknown!");
return null;
} else {
return pjp.proceed();
}
}
这篇关于AOP @Around:返回 BAD_REQUEST 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!