Skip to content

Commit

Permalink
Examples: add error handling example
Browse files Browse the repository at this point in the history
Related to #549
  • Loading branch information
Fishrock123 committed Jun 21, 2020
1 parent edac181 commit f2d1608
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ surf = { git = "https://github.com/Fishrock123/surf", branch = "deps-http-types-
serde = { version = "1.0.102", features = ["derive"] }
criterion = "0.3.1"
tempfile = "3.1.0"
url = "2.1.1"

[[test]]
name = "nested"
Expand Down
26 changes: 26 additions & 0 deletions examples/error_handling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use tide::{Request, Response, Result, StatusCode};
use tide::utils::After;

#[async_std::main]
async fn main() -> Result<()> {
tide::log::start();
let mut app = tide::new();

app.middleware(After(|mut res: Response| async move {
if let Some(err) = res.downcast_error::<url::ParseError>() {
let msg = err.to_string().to_owned();
res.set_status(StatusCode::ImATeapot);
res.set_body(format!("Teapot Status: {}", msg));
}
Ok(res)
}));

app.at("/").get(|_req: Request<_>| async move {
let path = url::Url::parse("")?;
Ok(format!("Path is {}", path))
});

app.listen("127.0.0.1:8080").await?;

Ok(())
}

0 comments on commit f2d1608

Please sign in to comment.