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

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
babastyle
  • 53
  • 1
  • 10
  • "_what is the best practice to prevent that_" Send the correct JSON format. – takendarkk Mar 23 '18 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 – babastyle Mar 23 '18 at 14:05
  • Possible duplicate of [Spring Boot REST service exception handling](https://stackoverflow.com/questions/28902374/spring-boot-rest-service-exception-handling) – statut Mar 23 '18 at 14:06

3 Answers3

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.

Chris
  • 3,437
  • 6
  • 40
  • 73
0

Use Spring ExceptionHandler to do that

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.

questionaire
  • 2,475
  • 2
  • 14
  • 28