簡體   English   中英

如何在Spring Boot Rest API中捕獲異常

[英]how to catch exception in spring boot rest api

我有以下代碼的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))。

防止這種情況的最佳做法是什么

使用Spring ExceptionHandler來做到這一點

您可以基於Exception類型指定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添加到主體即可。

我發現我需要在@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可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM