2012-11-15 26 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