你可以用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