我想設置與Spring MVC 3我建REST服務總是返回一個JSON對象,即使有事情,比如HTTP 406響應時我試過設置自定義錯誤處理程序在我的控制器,但它仍然不處理406錯誤,所以我仍然回到我的迴應默認的tomcat 406的HTML頁面。有一個更好的方法嗎?衝刺MVC 3 REST - 總是返回JSON對象
我的目標是始終返回JSON對象(而不是Tomcat的錯誤頁面),不管它是一個例外,我拋出或框架(如HTTP 406)拋出的異常。
@ControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(Throwable.class)
public void handleError(HttpServletResponse resp, HttpServletRequest req,
Throwable tr) throws Throwable {
//TODO this isn't working because valid exceptions like 406 don't have
//this annotation
if (AnnotationUtils.findAnnotation(tr.getClass(),
ResponseStatus.class) != null) {
throw tr;
}
//Do some stuff...get stuff out of Throwable object
ResponseEntity<MyCustomErrorType> respEntity =
new ResponseEntity<MyCustomErrorType>(tr);
...
new ObjectMapper().getFactory().createJsonGenerator(resp.getOutputStream())
.writeObject(respEntity);
}
}
嘗試將接受標頭設置爲應用程序/ json – Leon
我想處理接受標頭不正確的情況。 – xdhmoore