gpt4 book ai didi

java - 如何确保抛出 HttpClientErrorException 会导致 HTTP 400 响应?

转载 作者:行者123 更新时间:2023-11-29 04:07:16 25 4
gpt4 key购买 nike

当我抛出 HttpClientErrorException 时,根据下面的示例代码,我希望 HTTP 代码为 HTTP 400。相反,我得到一个 HTTP 500 响应代码和消息 400 BAD_REQUEST

import org.springframework.http.HttpStatus;

*****

@CrossOrigin
@RequestMapping(value = *****************, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "", notes = "Does Stuff")
public DTO save(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
******
try {
if (isError) {
handleSaveError(HttpStatus.BAD_REQUEST, "It was your fault, fix it.");
} else {
**** Success ****
}
} catch (IllegalStateException | IOException e) {
handleSaveError(HttpStatus.INTERNAL_SERVER_ERROR, "It was my fault, call back later.");
}
return dto;
}

private void handleSaveError(HttpStatus httpStatus, String responseMessage) {
String body = getResponseBody(responseMessage);
if (httpStatus.is4xxClientError()) {
log.debug(responseMessage);
throw new HttpClientErrorException(httpStatus, httpStatus.name(), body.getBytes(UTF_8), UTF_8);
}
if (httpStatus.is5xxServerError()) {
log.error(responseMessage);
throw new HttpServerErrorException(httpStatus, httpStatus.name(), body.getBytes(UTF_8), UTF_8);
}
}

最佳答案

在这里查看如何将异常映射到适当的状态代码。 https://www.baeldung.com/exception-handling-for-rest-with-spring

关于java - 如何确保抛出 HttpClientErrorException 会导致 HTTP 400 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57859519/

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