How to handle errors differently based on the URL? #675
-
I'm using poem-openapi and have mounted my API at let app = Route::new()
.at("/", get(index))
.nest("/api", api_service)
.nest("/doc", api_docs)
.at("/spec.json", api_spec); Is there any way to handle the errors differently based on URL path? And for any other URLs to respond with HTML output, so if there's an error (404, 400, 500, etc.) i want for this other non |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You could use middleware to handle it outside your Endpoint like so #[poem::async_trait]
impl<E: Endpoint> Endpoint for HandleEndpointErrorsMiddleware<E> {
type Output = Response;
async fn call(&self, req: Request) -> poem::Result<Self::Output> {
trace!("Entered cache controlling middleware");
let is_not_idempotent = req.method().is_safe();
let mut res = self.ep.get_response(req).await;
if res.status().is_client_error() || res.status().is_server_error() >= 300 { // or just res.status().as_u16() >= 300
if req.original_uri().path().starts_with("/api/"){
// Give Json errors
} else {
//Give HTML errors
}
}
}
} But I would actually personally recommend handling in the route/endpoint itself. If you want to abstract it away so it doesn't clutter the routes code then maybe you'd want a Uniform error type that implements |
Beta Was this translation helpful? Give feedback.
You could use middleware to handle it outside your Endpoint like so