您可以使用 Guice 的AOP 优势来绑定方法拦截器以捕获异常并将其序列化到 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
// ...
}
参考:https ://code.google.com/p/google-guice/wiki/AOP