如何在春季引导休息api中捕获异常

问题描述 投票:0回答:3

我有一个带有以下代码的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:意外字符('“'(代码34))。

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

json spring rest spring-boot exception
3个回答
0
投票

使用Spring ExceptionHandler来做到这一点


0
投票

您可以基于异常类型指定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添加到身体。


0
投票

我发现我需要在JsonProcessingException而不是JsonParseException捕捉@ExceptionHandlerJsonParseException延伸)

@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按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.