import org.http4k.core.ErrorHandler;
import org.http4k.core.Response;
import org.http4k.core.Status;
public class MyErrorHandler implements ErrorHandler {
@Override
public Response invoke(Throwable throwable) {
return Response.status(Status.INTERNAL_SERVER_ERROR)
.body("An internal server error occurred: " + throwable.getMessage());
}
}
import org.http4k.core.ErrorHandler;
import org.http4k.core.HttpHandler;
import org.http4k.core.Request;
import org.http4k.core.Response;
import org.http4k.core.Status;
public class MyMiddleware {
private final ErrorHandler errorHandler;
public MyMiddleware(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
public HttpHandler apply(HttpHandler next) {
return request -> {
try {
return next.handle(request);
} catch(Throwable throwable) {
return errorHandler.invoke(throwable);
}
};
}
}
import org.http4k.core.ErrorHandler;
import org.http4k.core.HttpHandler;
import org.http4k.core.Response;
import org.http4k.core.Status;
public class MyApp {
public static void main(String[] args) {
ErrorHandler errorHandler = throwable ->
Response.status(Status.INTERNAL_SERVER_ERROR)
.body("An internal server error occurred: " + throwable.getMessage());
HttpHandler app = new MyMiddleware(errorHandler)
.apply(Routes.routes(
endpoint1,
endpoint2,
));
app.handle(request);
}
}