首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring boot中各种数据不匹配时jackson反序列化错误的处理

spring boot中各种数据不匹配时jackson反序列化错误的处理
EN

Stack Overflow用户
提问于 2018-09-06 11:22:37
回答 3查看 6.2K关注 0票数 5

我知道这里有一些类似的问题,比如如何解析ENUM,如何解析自定义JSON结构。但在这里,我的问题是,当用户提交的JSON不是预期的时候,如何才能给出更好的消息。

代码如下:

代码语言:javascript
复制
@PutMapping
public ResponseEntity updateLimitations(@PathVariable("userId") String userId,
                                        @RequestBody LimitationParams params) {
  Limitations limitations = user.getLimitations();
  params.getDatasets().forEach(limitations::updateDatasetLimitation);
  params.getResources().forEach(limitations::updateResourceLimitation);
  userRepository.save(user);
  return ResponseEntity.noContent().build();
}

我期望的请求正文是这样的:

代码语言:javascript
复制
{
  "datasets": {"public": 10},
  "resources": {"cpu": 2}
}

但是当他们提交类似这样的东西时:

代码语言:javascript
复制
{
  "datasets": {"public": "str"}, // <--- a string is given
  "resources": {"cpu": 2}
}

响应将在日志中显示如下所示:

代码语言:javascript
复制
400 JSON parse error: Cannot deserialize value of type `java.lang.Integer` from String "invalid": not a valid Integer value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.lang.Integer` from String "invalid": not a valid Integer value

java.util.LinkedHashMap["public"]">Source: (PushbackInputStream); line: 1, column: 23

但我想要的是一个更具人类可读性的信息。

我试着在com.fasterxml.jackson.databind.exc.InvalidFormatException上使用ExceptionHandler,但它不起作用。

EN

回答 3

Stack Overflow用户

发布于 2018-09-06 12:17:11

您可以编写一个控制器建议来捕获异常并返回相应的错误响应。

下面是spring boot中的控制器建议示例:

代码语言:javascript
复制
@RestControllerAdvice
public class ControllerAdvice {
    @ExceptionHandler(InvalidFormatException.class)
    public ResponseEntity<ErrorResponse> invalidFormatException(final InvalidFormatException e) {
        return error(e, HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity <ErrorResponse> error(final Exception exception, final HttpStatus httpStatus) {
        final String message = Optional.ofNullable(exception.getMessage()).orElse(exception.getClass().getSimpleName());
        return new ResponseEntity(new ErrorResponse(message), httpStatus);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
public class ErrorResponse {
    private String errorMessage;
}
票数 1
EN

Stack Overflow用户

发布于 2020-04-07 16:40:11

真正的例外是org.springframework.http.converter.HttpMessageNotReadableException.拦截它,它就会起作用。

代码语言:javascript
复制
public ResponseEntity<String> handle(HttpMessageNotReadableException e) {
    return ResponseEntity.badRequest().body("your own message" + e.getMessage());
}
票数 0
EN

Stack Overflow用户

发布于 2020-06-04 19:54:49

下面的错误处理方法对我是有效的。

代码语言:javascript
复制
@ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity handleAllOtherErrors(HttpMessageNotReadableException formatException) {
        String error = formatException.getMessage().toString();
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52196053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档