[英]Spring rest Json web service with exception Handler
我遇到一個無條件的問題。 我在春季的Json上進行了REST服務。 我的服務假定可以使用“ Content-Type application / json”,但是每當我發出不具有content-type的請求時,它都會引發異常。
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
但是我正在使用@ExceptionHandler處理此異常,但是spring無法處理此異常,並且我的控件不在@ExceptionHandler方法中。
請指教! 我如何確保我的傳入請求需要發送內容類型標頭?
我想在我的@ExceptionHandler方法中捕獲此異常,以便可以發送帶有錯誤代碼的錯誤消息。
@RequestMapping(value = "/login", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<ReponseWrapper> login(@Valid LoginRequest loginRequest,
BindingResult results,) {
//any code
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public @ResponseBody Map<String, Object> handleUnsupportedMediaTypeException(HttpMediaTypeNotSupportedException ex) throws IOException {
Map<String, Object> map = Maps.newHashMap();
map.put("error", "Unsupported Media Type");
map.put("cause", ex.getLocalizedMessage());
map.put("supported", ex.getSupportedMediaTypes());
return map;
}
好吧,第一個問題是控制器方法上的@ExceptionHandler批注僅處理從控制器內部引發的異常。 您遇到的異常是在調用controller方法之前引發的,因此不會得到處理。
如果您遇到這樣的情況,它將得到處理:
@Controller
public class TestController {
@ResponseBody
@RequestMapping(value = "/test", consumes = APPLICATION_JSON_VALUE, produces =
APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseWrapper> test(LoginRequest request)
throws HttpMediaTypeNotSupportedException {
throw new HttpMediaTypeNotSupportedException("");
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public @ResponseBody Map<String, Object> handleUnsupportedMediaTypeException(
HttpMediaTypeNotSupportedException ex) throws IOException {
Map<String, Object> map = Maps.newHashMap();
map.put("error", "Unsupported Media Type");
map.put("cause", ex.getLocalizedMessage());
map.put("supported", ex.getSupportedMediaTypes());
return map;
}
}
我懷疑您將不得不擴展僅處理HttpMediaTypeNotSupportedException類型的ExceptionHandlerExceptionResolver。 或參閱此頁面 ,查看是否有幫助。
另外,請查看是否可以使用較新版本的Spring。
@ExceptionHanlder
批注不起作用,因為您的返回類型無效。 返回類型可以是String,它被解釋為視圖名稱或ModelAndView對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.