简体   繁体   中英

how to catch exception in spring boot rest api

i have a restcontroller with following Code

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

but if the json data doesn't match the Student object, or is wrong formatted an com.fasterxml.jackson.core.JsonParseException: Unexpected character ('"' (code 34)) ist thrown.

what is the best practice to prevent that

使用Spring ExceptionHandler来做到这一点

You could specify an ExceptionHandler based on Exception types and also apply the error codes you want to use.

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

Furthermore you could make use of javax.validation to validate the entity you receive and then Spring Boot will do all the validation automagically. Just add @Valid to the body.

I've found that I need to catch JsonProcessingException (which JsonParseException extends from) in the @ExceptionHandler rather than JsonParseException

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

}

Using JsonParseException in the above sample and nothing is caught, but using JsonProcessingException works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM