Md Zahid Raza
Md Zahid Raza

Reputation: 971

Ratpack Rest API ExceptionHandler

I want to have single ExceptionHandler for handling each exception while implementing REST API using ratpack. This ExceptionHandler will handle each runtime exception and send json response accordingly.

Is it possible in ratpack? In Spring we do that using @ControllerAdvice annotation. I want to implement similar behaviour using ratpack.

Thanks for helping.

Upvotes: 3

Views: 1703

Answers (2)

You can bind your own error handler, if you're using spring you can define a Bean of the type Action<BindingsSpec>, bind your spring application main and only need to declare your error handler as a bean to be reached by ratpack

Upvotes: 0

SDen
SDen

Reputation: 191

Well, the easiest way is to define your class who implements ratpack.error.ServerErrorHandler and bind it to ServerErrorHandler.class in registry.

Here is an example for ratpack app with Guice registry:

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

And Errorhandler like:

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

}

Upvotes: 5

Related Questions