2015-12-01 48 views
0

我想設置與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); 
    } 

} 
+0

嘗試將接受標頭設置爲應用程序/ json – Leon

+0

我想處理接受標頭不正確的情況。 – xdhmoore

回答

0

你好,你可以處理所有的異常拋出使用ExceptionMapper。 這是處理您的自定義異常的非常好的方法。 我跟貼:http://entityclass.in/rest/exceptionhandling.htm

+0

本文面向JAX-RS。我正在使用Spring MVC,而不是Jersey/JAX-RS。這將與Spring一起工作嗎? – xdhmoore

+0

嗨,我不確定這件事,它會在春天或不會的時候工作,很快就會更新 –