2012-11-15 39 views
1

我正在開發一個Web應用程序,該應用程序提供了許多REST端點Google Sitebricks。爲了最大限度地減少重複/類似的代碼,我希望配置sitebricks以在REST端點中執行的代碼每次引發異常時使用一致的Reply對象進行響應。發送一致的JSON響應以用Sitebricks報告異常

,而不是處理異常和產生在每個端點的自定義JSON響應,我想那sitebricks本身捕捉異常和返回是這樣的:那麼

{ 
    statusCode: 123, 
    message: "this could contain Exception.getMessage()", 
    stacktrace: "this could contain the full stacktrace" 
} 

Sitebricks將負責建立上述結構和填充在狀態碼和其他領域,例如基於註釋。

  • 我是否必須自己創建或者其他人已經這樣做?也許有什麼方法可以用Sitebricks做到這一點?
  • 是否有相當於Jersey's ExceptionMapper interface

回答

0

不完全回答你的問題,但我做了什麼來管理錯誤如下。

在父類我所有的REST端點,我已經聲明瞭以下方法:

protected Reply<?> error(String errorCode) { 
    logger.error(errorCode); 
    return Reply.with(new ErrorJSONReply(errorCode)).as(Json.class).headers(headers()).type("application/json; charset=utf-8"); 
} 

然後在我的所有端點我捕捉異常,並用這種方法來回答一般性錯誤。

希望有所幫助。

問候

0

你可以用Guice的AOP goodness結合的方法攔截器來捕獲和序列例外JSON ...

public class ReplyInterceptor implements MethodInterceptor { 

    @Retention(RetentionPolicy.RUNTIME) 
    @Target({ElementType.METHOD}) 
    @BindingAnnotation 
    public @interface HandleExceptionsAndReply { 
    } 


    public ReplyInterceptor() { 
    } 

    @Override 
    public Object invoke(MethodInvocation methodInvocation) throws Throwable { 
     try { 
      return methodInvocation.proceed(); 
     } catch (Throwable e) { 
      return handleException(e); 
     } 
    } 

    private Object handleException(Throwable e) { 
     Throwable cause = getCause(e); 
     return Reply.with(cause).as(Json.class); 
    } 


    @SuppressWarnings("ThrowableResultOfMethodCallIgnored") 
    private Throwable getCause(Throwable e) { 
     // org.apache.commons.lang3.exception.ExceptionUtils 
     Throwable rootCause = ExceptionUtils.getRootCause(e); 
     return rootCause == null ? e : rootCause; 
    } 
} 

綁定吧...

bindInterceptor(
     Matchers.any(), 
     Matchers.annotatedWith(ReplyInterceptor.HandleExceptionsAndReply.class), 
     new ReplyInterceptor(getProvider(ResponseBuilder.class)) 
); 

// OR bind to request method annotations... 

bindInterceptor(
     Matchers.any(), 
     Matchers.annotatedWith(Get.class), 
     new ReplyInterceptor(getProvider(ResponseBuilder.class)) 
); 

使用它...

@At("/foo/:id") 
@Get 
@ReplyInterceptor.HandleExceptionsAndReply 
public Reply<ApiResponse<Foo>> readFoo(@Named("id") String id) { 
    // fetch foo and maybe throw an exception 
    // ...   
} 

Ref:https://code.google.com/p/google-guice/wiki/AOP