Spring Boot中如何处理各种数据不匹配的杰克逊反序列化错误 [英] How to handle jackson deserialization error for all kinds of data mismatch in spring boot

查看:407
本文介绍了Spring Boot中如何处理各种数据不匹配的杰克逊反序列化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这里有一些有关如何解析ENUM,如何解析自定义JSON结构的类似问题.但是这里我的问题是,当用户提交的JSON与预期不符时,如何仅给出更好的消息.

I know there is some similar questions here about how to parse ENUM, how to parse customize JSON structure. But here my question is how to just give a better message when the user submit some JSON with is not as expected.

这是代码:

@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();
}

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

And the request body I expected is like this:

{
  "datasets": {"public": 10},
  "resources": {"cpu": 2}
}

但是当他们提交这样的内容时:

But when they submit something like this:

{
  "datasets": {"public": "str"}, // <--- a string is given
  "resources": {"cpu": 2}
}

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

The response will show something like this in logs:

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

at [来源:(PushbackInputStream);第1行,第23列](通过参考链:com.openbayes.api.users.LimitationParams ["datasets"]-> java.util.LinkedHashMap ["public"])

at [Source: (PushbackInputStream); line: 1, column: 23] (through reference chain: com.openbayes.api.users.LimitationParams["datasets"]->java.util.LinkedHashMap["public"])

但是我想要的是更易读的消息.

But what I want is a more human readable message.

我尝试对com.fasterxml.jackson.databind.exc.InvalidFormatException使用ExceptionHandler,但是它不起作用.

I tried to use ExceptionHandler for com.fasterxml.jackson.databind.exc.InvalidFormatException but it doesn't work.

推荐答案

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

You can write a controller advice to catch exceptions and return corresponding error response.

以下是春季引导中控制器建议的示例:

Here is an example of controller advice in spring boot :

@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;
}

这篇关于Spring Boot中如何处理各种数据不匹配的杰克逊反序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆