Search code examples
javaspringrestratpack

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.


Solution

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