![](/img/trans.png)
[英]How to pass the list of integers as json data to spring boot rest API?
[英]how to catch exception in spring boot rest api
我有以下代码的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来做到这一点
您可以基于Exception类型指定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
添加到主体即可。
我发现我需要在@ExceptionHandler
而不是JsonParseException
捕获JsonProcessingException
( 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
可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.