1

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

3
  • "what is the best practice to prevent that" Send the correct JSON format. Commented Mar 23, 2018 at 14:00
  • 1
    yeah for my webapp thats true, but what about People using other tools and send wrong data. I want to check the data and send and send a Response if ist not correctly json formatted Commented Mar 23, 2018 at 14:05
  • Possible duplicate of Spring Boot REST service exception handling Commented Mar 23, 2018 at 14:06

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use Spring ExceptionHandler to do that

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.