Ratpack Rest API 异常处理程序

Ratpack Rest API ExceptionHandler

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

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

感谢您的帮助。

嗯,最简单的方法是定义实现 ratpack.error.ServerErrorHandler 的 class 并将其绑定到 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();
    }
  }

}

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

可以访问的 bean