【发布时间】:2022-08-02 18:59:53
【问题描述】:
当我发送 restTemplate.postForEntity 我想捕捉异常
public DriverDTO create(CreateDriverForm createDriverForm) throws JsonProcessingException {
try {
...
ResponseEntity<DriverDTO> responseEntity =
restTemplate.postForEntity(\"http://localhost:8081/drivers\", entity, DriverDTO.class);
return responseEntity.getBody();
} catch (HttpClientErrorException exception) {
ExceptionResponseObject object = objectMapper.readValue(exception.getLocalizedMessage(), ExceptionResponseObject.class);
}
}
并将 exception.getLocalizedMessage() 从 Rest Api 转换为我的自定义异常响应对象:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExceptionResponseObject {
private LocalDateTime timestamp;
private int status;
private String errorName;
private String message;
}
但我收到以下错误:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of
`com.example.ekrany.responses.ExceptionResponseObject` (although at least one Creator exists):
no int/Int-argument constructor/factory method to deserialize from Number value (400)
at [Source: (String)\"400 : \"{\"timestamp\":\"2022-08-02T12:00:13.3734961\",\"status\":400,
\"errorName\":\"MethodArgumentNotValidException\",\"message\":\"[Email already exists]\"}\"\"; line: 1, column: 1]
我应该如何转换它?或者,当我发布任何表单并出现错误时,是否有更好的做法来处理来自 api 的 4xx 状态?
标签: spring exception servlets objectmapper