3

我希望在使用ratpack 实现REST API 时使用单个ExceptionHandler 来处理每个异常。这个 ExceptionHandler 将处理每个运行时异常并相应地发送 json 响应。

在ratpack中可以吗?在 Spring 中,我们使用 @ControllerAdvice 注释来做到这一点。我想使用 ratpack 实现类似的行为。

感谢您的帮助。

4

2 回答 2

5

好吧,最简单的方法是定义实现ratpack.error.ServerErrorHandler的类 并将其绑定到注册表中的ServerErrorHandler.class

这是带有 Guice 注册表的 ratpack 应用程序的示例:

public class Api {
  public static void main(String... args) throws Exception {
    RatpackServer.start(serverSpec -> serverSpec
      .serverConfig(serverConfigBuilder -> serverConfigBuilder
        .env()
        .build()
      )
      .registry(
        Guice.registry(bindingsSpec -> bindingsSpec
          .bind(ServerErrorHandler.class, ErrorHandler.class)
        )
      )
      .handlers(chain -> chain
        .all(ratpack.handling.RequestLogger.ncsa())
        .all(Context::notFound)
      )
    );
  }
}

和错误处理程序喜欢:

class ErrorHandler implements ServerErrorHandler {

  @Override public void error(Context context, Throwable throwable) throws Exception {
    try {
      Map<String, String> errors = new HashMap<>();

      errors.put("error", throwable.getClass().getCanonicalName());
      errors.put("message", throwable.getMessage());

      Gson gson = new GsonBuilder().serializeNulls().create();

      context.getResponse().status(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).send(gson.toJson(errors));
      throw throwable;
    } catch (Throwable throwable1) {
      throwable1.printStackTrace();
    }
  }

}
于 2017-05-05T16:11:43.157 回答
0

您可以绑定您自己的错误处理程序,如果您使用的是 spring,您可以定义一个 Bean 类型Action<BindingsSpec>,绑定您的 spring 应用程序 main 并且只需要将您的错误处理程序声明为由 ratpack 访问的 bean

于 2018-03-22T21:28:30.963 回答