我有一个带有以下代码的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来做到这一点
您可以基于异常类型指定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
添加到身体。
我发现我需要在JsonProcessingException
而不是JsonParseException
捕捉@ExceptionHandler
(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);
}
}
在上面的示例中使用JsonParseException
并没有捕获任何内容,但使用JsonProcessingException
按预期工作。