From 148e175fa725ff2a718137210c6b293171bc1e36 Mon Sep 17 00:00:00 2001 From: shouya <526598+shouya@users.noreply.github.com> Date: Mon, 5 Aug 2024 16:00:53 +0900 Subject: [PATCH] improve source error message --- src/server/endpoint.rs | 10 ++++++---- src/util.rs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/server/endpoint.rs b/src/server/endpoint.rs index 49c114f..798f80d 100644 --- a/src/server/endpoint.rs +++ b/src/server/endpoint.rs @@ -207,9 +207,10 @@ impl EndpointService { async fn handle(self, mut req: Request) -> Result { // infallible let param: EndpointParam = req.extract_parts().await.unwrap(); - let feed = self.run(param).await.map_err(|e| { - (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response() - })?; + let feed = self + .run(param) + .await + .map_err(|e| e.as_response().into_response())?; let resp = feed.into_response(); Ok(resp) } @@ -242,7 +243,8 @@ impl EndpointService { let source = self.find_source(¶m.source)?; let feed = source .fetch_feed(Some(&self.client), param.base.as_ref()) - .await?; + .await + .map_err(|e| Error::FetchSource(Box::new(e)))?; let mut context = FilterContext::new(); if let Some(limit_filters) = param.limit_filters { context.set_limit_filters(limit_filters); diff --git a/src/util.rs b/src/util.rs index 78fd422..13e2466 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,3 +1,4 @@ +use http::StatusCode; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use url::Url; @@ -118,10 +119,26 @@ pub enum Error { #[error("Unsupported feed format: {0}")] UnsupportedFeedFormat(String), + #[error("Failed fetching source: {0}")] + FetchSource(Box), + #[error("{0}")] Message(String), } +impl Error { + pub fn as_response(self) -> (StatusCode, String) { + match self { + Error::HttpStatus(status, url) => { + let body = format!("{}: {}", status, url); + (status, body) + } + Error::Message(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg), + Error::FeedParse(msg) => (StatusCode::BAD_REQUEST, msg.to_string()), + } + } +} + #[derive( JsonSchema, Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash, )]