我正在使用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 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 response = new ResponseEntity(result, status);
return response;
}
@ExceptionHandler({NullPointerException.class, EOFException.class})
@ResponseBody
public ResponseEntity 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 response = new ResponseEntity(result, status);
return response;
}