小智 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)
归档时间: |
|
查看次数: |
1653 次 |
最近记录: |