我正在研究一个简单的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 误差DTO {
    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 误差DTO handleException(Exception exception) {
        log.error(exception.getMessage(), exception);
        return 误差DTO.builder()
                .code(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .message("Unexpected error!")
                .text("This is the text!")
                .build();
    }
}

When I call this API from Postman everything is fine and I get 500 Internal Server 误差 with response body:

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

但问题是当我try 从另一个微服务调用此API时.我这样使用Rest模板:

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

I receive only 500 Internal Server 误差, I can't find the Response Body

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

有人能解释一下如何在其他服务中(而不仅仅在postman 中)接收响应机构吗?谢谢!

推荐答案

这取决于您遇到的问题.

(1) You get the response, but you don't know how to read it

使用HttpClientErrorException.getResponseBodyAsString()或类似的方法.

或者,您可以用implement ResponseErrorHandlerrestTemplate.

(2) Server doesn't send you the response in JSON format

添加值为MediaType.APPLICATION_JSON的"Accept"请求标头,让Spring知道您的客户支持SON.

Springtry 猜测响应内容类型.根据配置,它会退回到plain/text或其他没有主体的"错误"类型.

Java相关问答推荐

通过推送通知向自己发送Matrix消息

使用json参数通过单击jSP文件中的按钮来运行server时出现问题

表格栏上的事件过滤器在PFA中不起作用

如何在SystemiccationRetryListenerSupport中获得类级别的spring retryable annotation中指定的标签?

Java List with all combinations of 8 booleans

为什么不应用类型推断?

对Java中的通配符参数的混淆

更新GWT 2.5.1到2.11.0和sencha GXT 3.1.1到4.1时出现错误

将带有js文件的 bootstrap 程序导入maven项目时出错

测试何时使用Mockito强制转换对象会导致ClassCastException

用OSQL创建索引

类型集合的Jackson JsonNode:类型引用的对象读取器应该是Singleton吗?

继续收到错误SQLJDBC EXCEPTION执行";org.springframework.dao.InvalidDataAccessResourceUsageException:&

Kotlin Val是否提供了与Java最终版相同的可见性保证?

在Oracle JDBC连接中,连接失效和身份验证失效是什么意思?

Java 21中泛型的不兼容更改

判断重复的两个二维表算法?

RestTemplate Bean提供OkHttp3ClientHttpRequestFactory不支持Spring Boot 3中的请求正文缓冲

在Java中将对象&转换为&q;HashMap(&Q)

使用StringBuilder和append方法创建字符串时Java字符串内部方法的问题