2011-07-30 39 views
6
我無法處理我的RESTful服務異常

JAX-RS和EJB異常處理

@Path("/blah") 
@Stateless 
public class BlahResource { 
    @EJB BlahService blahService; 

    @GET 
    public Response getBlah() { 
     try { 
      Blah blah = blahService.getBlah(); 
      SomeUtil.doSomething(); 
      return blah; 
     } catch (Exception e) { 
      throw new RestException(e.getMessage(), "unknown reason", Response.Status.INTERNAL_SERVER_ERROR); 
     } 
    } 
} 

RestException是映射例外:

public class RestException extends RuntimeException { 
    private static final long serialVersionUID = 1L; 
    private String reason; 
    private Status status; 

    public RestException(String message, String reason, Status status) { 
     super(message); 
     this.reason = reason; 
     this.status = status; 
    } 
} 

這裏是RestException異常映射器:

@Provider 
public class RestExceptionMapper implements ExceptionMapper<RestException> { 

    public Response toResponse(RestException e) { 
     return Response.status(e.getStatus()) 
      .entity(getExceptionString(e.getMessage(), e.getReason())) 
      .type("application/json") 
      .build(); 
    } 

    public String getExceptionString(String message, String reason) { 
     JSONObject json = new JSONObject(); 
     try { 
      json.put("error", message); 
      json.put("reason", reason); 
     } catch (JSONException je) {} 
     return json.toString(); 
    } 

} 

現在,對我來說最重要的是提供響應代碼和一些響應文本u SER。但是,當引發RestException時,這會導致EJBException(帶有消息「EJB拋出一個意外的(未聲明的)異常...」),並且該servlet僅將響應代碼返回給客戶端(以及而不是我在RestException中設置的響應文本)。

當我的RESTful資源不是EJB時,這完美地工作......任何想法?我一直在爲此工作數小時,而且我都沒有想法。

謝謝!

+0

我有一個類似的用例,我的EJB引發了WebApplicationException並且它可以工作。 – lili

回答

0

類似的情況下對我的作品的時候RestException延伸javax.ws.rs.WebApplicationException

5

這個問題似乎與EJB異常處理的連接。根據任何system exception(即 - 任何RuntimeException未明確標記爲Application Exception)從託管bean中引發的請求,將打包到EJBException中,如果需要的話,稍後將打包到拋出給客戶端的RemoteException中。這是一個情況下,你似乎是,爲了避免您可以:

  • 改變你的RestException成檢查異常,並處理它這樣
  • 使用@ApplicationException註釋您RestException
  • 創建EJBExceptionMapper並從中提取需要的信息(RestfulException) e.getCause()