gpt4 book ai didi

spring - AOP @Around : return BAD_REQUEST response

转载 作者:行者123 更新时间:2023-12-01 03:40:46 25 4
gpt4 key购买 nike

在 Spring rest 应用程序中,每个 URL 都必须以应用程序 ID (appId) 开头。此 appId 必须在每个休息服务中进行验证。我没有复制代码,而是尝试使用 @Around 建议创建一个 @Aspect。这是在任何休息方法之前正确执行的。

但是,如果应用程序 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();
}
}
}

最佳答案

您需要访问 HttpServletResponse并使用它来发送错误代码。您可以通过 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();
}
}

关于spring - AOP @Around : return BAD_REQUEST response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31075594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com