如何在 Spring Boot 中创建 500 错误的响应正文?

问题描述 投票:0回答:1

我正在开发一个简单的 Spring Boot 项目,我想为 500 错误创建一个响应对象。

这是控制器:

@RestController
@Slf4j
public class DataController {
    @PostMapping(value = "/data", consumes = "application/json", produces = "application/json")
    DataResponse createData(@RequestBody List<ClientRequest> completeRequest) throws Exception {
        log.info("completeRequest = {}", completeRequest);
        throw new Exception();
    }

错误

@Data
@Builder
@AllArgsConstructor
public class ErrorDTO {
    private final String code;
    private final String message;
    private final String text;
}

异常处理程序:

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorDTO handleException(Exception exception) {
        log.error(exception.getMessage(), exception);
        return ErrorDTO.builder()
                .code(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .message("Unexpected error!")
                .text("This is the text!")
                .build();
    }
}

当我从 Postman 调用此 API 时,一切正常,但我收到 500 Internal Server Error 和响应正文:

{
    "code": "Internal Server Error",
    "message": "Unexpected error!",
    "text": "This is the text!"
}

但问题是当我尝试从另一个微服务调用这个 API 时。我正在这样使用 RestTemplate:

try {
    ResponseEntity<ResponseDemo> result = restTemplate.postForEntity(uri, requestDemos, ResponseDemo.class);
    log.info("Success response: {}", result);
    ResponseDemo body = result.getBody();
    log.info("body= {}", body);
} catch (HttpClientErrorException | HttpServerErrorException ex) {
    log.error("ERROR at POST {}", ex.getMessage());
}

我只收到 500 内部服务器错误,我找不到响应正文

{
    "code": "Internal Server Error",
    "message": "Unexpected error!",
    "text": "This is the text!"
}

有人可以解释如何在其他服务中接收响应正文,而不仅仅是在 Postman 中吗?谢谢!

java spring spring-boot http-status-code-500
1个回答
0
投票

取决于您遇到的问题。

(1) 您收到回复,但不知道如何阅读

使用

HttpClientErrorException.getResponseBodyAsString()
或者您可以为您的
ResponseErrorHandler
实现
restTemplate

(2) 服务器未向您发送 JSON 格式的响应

您需要“Accept”请求标头来让 Spring 知道,您的客户端支持 JSON。

Spring 尝试猜测响应内容类型。根据配置,它会退回到纯文本/文本或其他一些没有正文的“错误”类型。

© www.soinside.com 2019 - 2024. All rights reserved.