[英]In Spring, Is there a way to return different Content-Type values for the header?
當我遇到錯誤時,我想將produces = text/plain
為produces = application/json
。
@RequestMapping(value = "/v0.1/content/body", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public Object getBody(@RequestParam(value = "pageid") final List<String> pageid, @RequestParam(value = "test") final String test) {
if (!UUIDUtil.isValid(pageid)) {
Map map = new HashMap();
map.put("reason", "bad pageId");
map.put("pageId", pageId);
map.put("test", test);
return new ResponseEntity<Object>(map, HttpStatus.BAD_REQUEST);
}
return "hello";
}
這段代碼的問題在於,當我發送無效的pageId時,它不會將錯誤顯示為json。 它給我一個HTTP 406錯誤不可接受,因為它期望產生文本/純文本,但我沒有返回String。
處理錯誤的最干凈方法是使用@ExceptionHandler
:
@ExceptionHandler(EntityNotFoundException.class) //Made up that exception
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ErrorObject handleException(Exception e) {
return new ErrorObject(e.getMessage());
}
然后,假設您已正確配置解析器並將正確的JSON序列化庫放入類路徑中,則ErrorObject
的實例將作為JSON響應返回給客戶端。
當然,您可以根據需要設置多個@ExceptionHandler
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.