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

How to I make sure that throwing a HttpClientErrorException causes an HTTP 400 response?

当我抛出 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 boot rest 服务创建全局处理程序

使用 Spasoje Petronijević 提供的有关 link 的信息,我在 ControllerAdvice class 中创建了一个处理程序方法,并捕获了一个自定义异常 class。

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());
    }
}