Browse Source

Error handling updates

master
Dylan Baker 3 years ago
parent
commit
bd723d6922
2 changed files with 26 additions and 8 deletions
  1. 5
    2
      src/fs.rs
  2. 21
    6
      src/main.rs

+ 5
- 2
src/fs.rs View File

@@ -45,8 +45,11 @@ async fn read_post_from_disk(path: &PathBuf) -> Result<String, Error> {
45 45
     match read_to_string(&path).await {
46 46
         Ok(c) => Ok(c),
47 47
         Err(_) => Err(Error::new(
48
-            ErrorKind::Other,
49
-            format!("Error reading post {:?}", &path),
48
+            ErrorKind::NotFound,
49
+            format!(
50
+                "Can't find post with the id '{}'",
51
+                path.file_stem().unwrap().to_str().unwrap()
52
+            ),
50 53
         )),
51 54
     }
52 55
 }

+ 21
- 6
src/main.rs View File

@@ -65,12 +65,27 @@ async fn main() -> std::io::Result<()> {
65 65
     let mut app = tide::new();
66 66
 
67 67
     app.with(After(|mut res: Response| async {
68
-        if let Some(err) = res.downcast_error::<async_std::io::Error>() {
69
-            let mut context = Context::new();
70
-            context.insert("error", &err.to_string());
71
-            res.set_body(render("error.html", &context)?);
72
-            res.set_status(StatusCode::InternalServerError);
73
-        }
68
+        let mut context = Context::new();
69
+
70
+        match res.downcast_error::<async_std::io::Error>() {
71
+            Some(e) => {
72
+                context.insert("error", &e.to_string());
73
+                let status = if let ErrorKind::NotFound = e.kind() {
74
+                    StatusCode::NotFound
75
+                } else {
76
+                    StatusCode::InternalServerError
77
+                };
78
+                res.set_body(render("error.html", &context)?);
79
+                res.set_status(status);
80
+            }
81
+            None => match res.status() {
82
+                StatusCode::NotFound => {
83
+                    context.insert("error", "Page not found");
84
+                    res.set_body(render("error.html", &context)?);
85
+                }
86
+                _ => {}
87
+            },
88
+        };
74 89
 
75 90
         Ok(res)
76 91
     }));

Loading…
Cancel
Save