Skip to main content

basic/
error_handling.rs

1use std::sync::atomic::{AtomicUsize, Ordering};
2
3use afire::{Content, Method, Response, Server, Status};
4
5use crate::Example;
6
7// You can run this example with `cargo run --example basic -- error_handling`
8
9// Don't crash thread from a panic in a route
10// This does not apply to the error handler itself
11// afire will catch any panic in a route and return a 500 error by default
12
13pub struct ErrorHandling;
14
15impl Example for ErrorHandling {
16    fn name(&self) -> &'static str {
17        "error_handling"
18    }
19
20    fn exec(&self) {
21        // Create a new Server instance on localhost port 8080
22        let mut server = Server::<()>::new("localhost", 8080);
23
24        // Define a route that will panic
25        server.route(Method::GET, "/panic", |_req| panic!("This is a panic!"));
26
27        // Give the server a main page
28        server.route(Method::GET, "/", |_req| {
29            Response::new()
30                .text(r#"<a href="/panic">PANIC</a>"#)
31                .content(Content::HTML)
32        });
33
34        // You can optionally define a custom error handler
35        // This can be defined anywhere in the server and will take affect for all routes
36        // Its like a normal route, but it will only be called if the route panics
37        let errors = AtomicUsize::new(1);
38        server.error_handler(move |_state, _req, err| {
39            Response::new()
40                .status(Status::InternalServerError)
41                .text(format!(
42                    "<h1>Internal Server Error #{}</h1><br>Panicked at '{}'",
43                    errors.fetch_add(1, Ordering::Relaxed),
44                    err
45                ))
46                .content(Content::HTML)
47        });
48
49        // You can now goto http://localhost:8080/panic
50        // This will cause the route to panic and return a 500 error
51
52        // Start the server
53        // This will block the current thread
54        server.start().unwrap();
55    }
56}