Ratpack Rest API 异常处理程序

Md *_*aza 3 java rest spring ratpack

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

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

谢谢你的帮助。

小智 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)
      )
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

和错误处理程序类似:

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();
    }
  }

}
Run Code Online (Sandbox Code Playgroud)