当我抛出一个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
请参阅 https://github.com/s2agrahari/global-excpetion-handler-spring-boot 为 Spring 引导休息服务创建全局处理程序
使用 Spasoje Petronijević 提供的链接上的信息,我在 ControllerAdvice 类中创建了一个处理程序方法,并捕获了一个自定义异常类。
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import stuff.exception.RequestException;
@ControllerAdvice
public class HTTPExceptionHandler {
@ExceptionHandler({ RequestException.class })
public ResponseEntity<String> handleBadRequestException(RequestException ex, HttpServletRequest request) {
return ResponseEntity
.status(ex.getHttpStatus())
.body(ex.getBody());
}
}