我在春季靴子里有休息服务。我有一个帖子方法。在post方法中,我接受json。这是工作。但是当客户端向我发送userId字段的字符(短)时,我采取json解析错误。在异常之前我可以控制它吗?我想自定义错误消息,但异常消息太复杂了。
<%= f.submit foo.persisted? ? 'Update Foo' : 'Create Foo' %>
错误讯息是:
JSON解析错误:无法从字符串“a”反序列化类型@RequestMapping(value = "/customers", method = RequestMethod.POST)
public ResponseEntity<?> insertCustomer(@Valid @RequestBody InsertParams
params)
/*
*/}
public class InsertParams() {
private Short userId;
}
的值:不是有效的短值
答案 0 :(得分:0)
我是这样做的。
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ExceptionResponse>
handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
String fieldName = "";
String message = "";
if (!(ex.getCause() instanceof JsonMappingException)) {
return new ResponseEntity<ExceptionResponse>(HttpStatus.BAD_REQUEST);
}
JsonMappingException e = (JsonMappingException) ex.getCause();
for (JsonMappingException.Reference reference : e.getPath()) {
fieldName = reference.getFieldName();
}
if (fieldName.toLowerCase().contains("date"))
message = fieldName + " format exception. Should be yyyy-MM-dd";
else
message = fieldName + " can not take characters.";
ExceptionResponse er = new ExceptionResponse();
er.setResult("Failure");
er.setStatus(HttpStatus.BAD_REQUEST.value());
er.setDescription(message);
return new ResponseEntity<ExceptionResponse>(er, HttpStatus.BAD_REQUEST);