使用Spring MVC,接受带有错误JSON的POST请求会导致返回默认的400错误代码服务器页面
我正在开发一个 REST API。收到带有错误JSON的POST消息(例如{sdfasdfasdf})会导致Spring返回400错误请求错误的默认服务器页面。我不想返回页面,我想返回自定义 JSON 错误对象。
当使用@ExceptionHandler引发异常时,我可以执行此操作。因此,如果它是一个空白请求或空白JSON对象(例如{}),它将抛出一个NullPointerException,我可以使用我的 ExceptionHandler捕获它并做任何我想做的事情。
那么问题来了,当Spring只是无效的语法时,它实际上并没有抛出异常......至少不是我能看到的。它只是从服务器返回默认的错误页面,无论是Tomcat,Glassfish等。
所以我的问题是,我如何“拦截”Spring并导致它使用我的异常处理程序或以其他方式阻止错误页面显示并返回JSON错误对象?
这是我的代码:
@RequestMapping(value = "/trackingNumbers", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public ResponseEntity<String> setTrackingNumber(@RequestBody TrackingNumber trackingNumber) {
HttpStatus status = null;
ResponseStatus responseStatus = null;
String result = null;
ObjectMapper mapper = new ObjectMapper();
trackingNumbersService.setTrackingNumber(trackingNumber);
status = HttpStatus.CREATED;
result = trackingNumber.getCompany();
ResponseEntity<String> response = new ResponseEntity<String>(result, status);
return response;
}
@ExceptionHandler({NullPointerException.class, EOFException.class})
@ResponseBody
public ResponseEntity<String> resolveException()
{
HttpStatus status = null;
ResponseStatus responseStatus = null;
String result = null;
ObjectMapper mapper = new ObjectMapper();
responseStatus = new ResponseStatus("400", "That is not a valid form for a TrackingNumber object " +
"({\"company\":\"EXAMPLE\",\"pro_bill_id\":\"EXAMPLE123\",\"tracking_num\":\"EXAMPLE123\"})");
status = HttpStatus.BAD_REQUEST;
try {
result = mapper.writeValueAsString(responseStatus);
} catch (IOException e1) {
e1.printStackTrace();
}
ResponseEntity<String> response = new ResponseEntity<String>(result, status);
return response;
}