【问题标题】:how to catch exception in spring boot rest api如何在spring boot rest api中捕获异常
【发布时间】:2018-09-02 05:30:11
【问题描述】:

我有一个带有以下代码的restcontroller

@RequestMapping(method = RequestMethod.POST, value = "/student")
public void addTopic(@RequestBody Student student) {
    student.setPassword(bCryptPasswordEncoder.encode(student.getPassword()));
    studentService.addStudent(student);
}

但如果 json 数据与 Student 对象不匹配,或者格式错误,则会抛出 com.fasterxml.jackson.core.JsonParseException: Unexpected character ('"' (code 34))。

防止这种情况的最佳做法是什么

【问题讨论】:

  • "防止这种情况的最佳做法是什么" 发送正确的 JSON 格式。
  • 对我的 webapp 来说是的,那是真的,但是人们使用其他工具并发送错误数据呢?如果不是正确的 json 格式,我想检查数据并发送和发送响应

标签: json spring rest spring-boot exception


【解决方案1】:

使用 Spring ExceptionHandler 来做到这一点

【讨论】:

    【解决方案2】:

    您可以根据异常类型指定 ExceptionHandler 并应用您要使用的错误代码。

    @ExceptionHandler(JsonParseException.class)
    public JacksonExceptionHandler {
      public ResponseEntity<String> handleError(final Exception exception) {
        HttpStatus status = HttpStatus.BAD_REQUEST;
        if (exception != null) {
            LOGGER.warn("Responding with status code {} and exception message {}", status, exception.getMessage());
            return new ResponseEntity<>(exception.getMessage(), status);
        }
    }
    

    此外,您可以使用javax.validation 来验证您收到的实体,然后 Spring Boot 将自动完成所有验证。只需将@Valid 添加到正文即可。

    【讨论】:

      【解决方案3】:

      我发现我需要在 @ExceptionHandler 而不是 JsonParseException 中捕获 JsonProcessingExceptionJsonParseException 扩展自)

      @ControllerAdvice
      public class FeatureToggleControllerAdvice {
      
          @ExceptionHandler(JsonProcessingException.class)
          public ResponseEntity<JSONAPIDocument> handleJsonParseException(JsonProcessingException ex) {
              final Error error = new Error();
              error.setId(UUID.randomUUID().toString());
              error.setStatus(HttpStatus.BAD_REQUEST.toString());
              error.setTitle(ex.getMessage());
      
              return new ResponseEntity<>(JSONAPIDocument
                      .createErrorDocument(Collections.singleton(error)), HttpStatus.NOT_FOUND);
          }
      
      }
      

      在上面的示例中使用JsonParseException 并没有捕获任何内容,但是使用JsonProcessingException 可以按预期工作。

      【讨论】:

        猜你喜欢
        • 2018-01-24
        • 1970-01-01
        • 2018-01-16
        • 2019-08-07
        • 2020-08-04
        • 2022-11-29
        • 1970-01-01
        • 2016-12-16
        • 2020-06-05
        相关资源
        最近更新 更多