我正在研究一个简单的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 中)接收响应机构吗?谢谢!