Переглянути джерело

Error handling updates

master
Dylan Baker 3 роки тому
джерело
коміт
bd723d6922
2 змінених файлів з 26 додано та 8 видалено
  1. 5
    2
      src/fs.rs
  2. 21
    6
      src/main.rs

+ 5
- 2
src/fs.rs Переглянути файл

45
     match read_to_string(&path).await {
45
     match read_to_string(&path).await {
46
         Ok(c) => Ok(c),
46
         Ok(c) => Ok(c),
47
         Err(_) => Err(Error::new(
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 Переглянути файл

65
     let mut app = tide::new();
65
     let mut app = tide::new();
66
 
66
 
67
     app.with(After(|mut res: Response| async {
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
         Ok(res)
90
         Ok(res)
76
     }));
91
     }));

Завантаження…
Відмінити
Зберегти