dioxus
dioxus copied to clipboard
Having A Catch-All Route Produce A 404 Status Code
As an example router:
#[derive(Debug, Clone, Routable, PartialEq)]
#[rustfmt::skip]
enum Route {
#[layout(Frame)]
#[route("/")]
Home {},
#[route("/about")]
About {},
#[route("/:..route")]
PageNotFound { route: Vec<String> },
}
And using the errors example:
fn app() -> Element {
rsx! {
ErrorBoundary {
handle_error: move |err| {
// To ensure the HTTP status is still set properly, we need to call `commit_error_status`
let http_error = FullstackContext::commit_error_status(err.error().unwrap());
// and then we can render some pretty fallback UI
rsx! { "An error occurred! {http_error:?}" }
},
Post {}
}
}
}
fn Post() -> Element {
let post_data = use_loader(move || get_post())?;
rsx! { p { "{post_data" } }
}
The ErrorBoundary is never hit, because the status code sent is always 200 OK.
Is there a straightforward way to have a catch-all route send an error so that the ErrorBoundary is activated?
You can call FullstackContext::commit_error_status inside of a hook in the PageNotFound component with an error that has the 404 status code like a CapturedError created from a http::StatusCode
I did it a bit more explicitly:
if let Some(mut context) = dioxus_fullstack::FullstackContext::current() {
context.set_current_http_status(HttpError::new(StatusCode::NOT_FOUND, ""));
}