Skip to content

Commit 38a9891

Browse files
committed
cast errors to responses
1 parent b23d97a commit 38a9891

File tree

2 files changed

+46
-11
lines changed

2 files changed

+46
-11
lines changed

src/middleware/logger.rs

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,30 @@ impl RequestLogger {
3030
let method = ctx.method().to_string();
3131
log::trace!("IN => {} {}", method, path);
3232
let start = std::time::Instant::now();
33-
let res = next.run(ctx).await?;
34-
let status = res.status();
35-
log::info!(
36-
"{} {} {} {}ms",
37-
method,
38-
path,
39-
status,
40-
start.elapsed().as_millis()
41-
);
42-
Ok(res)
33+
match next.run(ctx).await {
34+
Ok(res) => {
35+
let status = res.status();
36+
log::info!(
37+
"{} {} {} {}ms",
38+
method,
39+
path,
40+
status,
41+
start.elapsed().as_millis()
42+
);
43+
Ok(res)
44+
}
45+
Err(err) => {
46+
let msg = err.to_string();
47+
log::error!(
48+
"{} {} {} {}ms",
49+
msg,
50+
method,
51+
path,
52+
start.elapsed().as_millis()
53+
);
54+
Err(err)
55+
}
56+
}
4357
}
4458
}
4559

src/server/mod.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,28 @@ impl<State: Sync + Send + 'static> HttpService for Service<State> {
347347
fn respond(&self, _conn: (), req: http_service::Request) -> Self::ResponseFuture {
348348
let req = Request::new(self.state.clone(), req, Vec::new());
349349
let service = self.clone();
350-
Box::pin(async move { Ok(service.call(req).await?.into()) })
350+
Box::pin(async move {
351+
match service.call(req).await {
352+
Ok(value) => {
353+
let res = value.into();
354+
// We assume that if an error was manually cast to a
355+
// Response that we actually want to send the body to the
356+
// client. At this point we don't scrub the message.
357+
Ok(res)
358+
}
359+
Err(err) => {
360+
let mut res = http_types::Response::new(err.status());
361+
res.set_content_type(http_types::mime::PLAIN);
362+
// Only send the message if it is a non-500 range error. All
363+
// errors default to 500 by default, so sending the error
364+
// body is opt-in at the call site.
365+
if !res.status().is_server_error() {
366+
res.set_body(err.to_string());
367+
}
368+
Ok(res)
369+
}
370+
}
371+
})
351372
}
352373
}
353374

0 commit comments

Comments
 (0)