【问题标题】:How to conver getLocalizedMessage() to Custom Exception Object - MismatchedInputException如何将 getLocalizedMessage() 转换为自定义异常对象 - MismatchedInputException
【发布时间】: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


    【解决方案1】:

    因为如果它的错误它不能转换为驱动程序TO。 试试这样

        ResponseEntity<String> responseEntity =
                    restTemplate.postForEntity("http://localhost:8081/drivers", entity, String.class);
    if (responseEntity.statusCode == 200){
    objectMapper.readValue(responseEntity.getBody(), DriverDTO.class);
    }
    else{
    ExceptionResponseObject object = objectMapper.readValue(exception.getLocalizedMessage(), ExceptionResponseObject.class);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-01
      • 2016-08-17
      • 2011-06-02
      • 2017-09-19
      • 2014-02-15
      • 1970-01-01
      • 2011-01-15
      • 2014-04-17
      • 2018-05-08
      相关资源
      最近更新 更多