babastyle
babastyle

Reputation: 53

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

Upvotes: 1

Views: 1978

Answers (3)

Chris
Chris

Reputation: 3657

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.

Upvotes: 1

questionaire
questionaire

Reputation: 2585

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.

Upvotes: 0

Hassan BELHADJ
Hassan BELHADJ

Reputation: 23

Use Spring ExceptionHandler to do that

Upvotes: 0

Related Questions