2017-02-15 5 views
1

ratpackを使用してREST APIを実装する際に、各例外を処理する単一のExceptionHandlerが必要です。このExceptionHandlerは各実行時例外を処理し、それに応じてjson応答を送信します。Ratpack Rest API ExceptionHandler

ラットパックでも可能ですか? Springでは@ControllerAdviceアノテーションを使用してそれを行います。 ratpackを使用して同様の動作を実装したいと思います。

ありがとうございます。

答えて

2

まあ、最も簡単な方法は、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) 
    ) 
    ); 
    } 
} 

とのErrorHandler:

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

}