我正在开发一个 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;
}