title | timestamp | author | published | description | tags | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Rocket: 404 page with static content |
2024-05-02 11:30:01 -0700 |
szabgab |
true |
|
If the user visits a path on our Rocket-based site that does not match any of the routes, by default, Rocket will show a very simple page saying 404: Not Found and The requested resource could not be found..
You might want to have a more fancy page.
In this example you can see how to do that.
We only need Rocket for this.
{% include file="examples/rocket/http-404-page-with-static-content/Cargo.toml" %}
We could embed the HTML in our Rust file, but it is better to have it in a separate file with html
extension. That will allow a designer
to make it nice without any interaction with Ruts.
Se we have it in a separate file.
Note: I am not a designer.
{% include file="examples/rocket/http-404-page-with-static-content/src/templates/404.html" %}
{% include file="examples/rocket/http-404-page-with-static-content/src/main.rs" %}
{% include file="examples/rocket/http-404-page-with-static-content/src/tests.rs" %}
We implement the function that will be called by Rocket when all routes were tried and none of them matched.
It looks exactly like a regular route, but it is marked with catch(404)
.
#[catch(404)]
fn not_found() -> RawHtml<&'static str> {
const BODY: &str = include_str!("templates/404.html");
RawHtml(BODY)
}
The include_str! embeds the external file into the compiled binary during compilation.
We also need to register the catchers using the register method and the catchers! macro:
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index])
.register("/", catchers![not_found])
}
In the tests we can verify that the response status for the main route is Ok and for an arbitrary other path is NotFound.
In the main route we checked that the returned page is exactly as we expect.
In the 404 route we demonstrate how to check that some content is in the returned HTML.