error_handle.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //! This example showcases how to use the ErrorBoundary component to handle errors in your app.
  2. //!
  3. //! The ErrorBoundary component is a special component that can be used to catch panics and other errors that occur.
  4. //! By default, Dioxus will catch panics during rendering, async, and handlers, and bubble them up to the nearest
  5. //! error boundary. If no error boundary is present, it will be caught by the root error boundary and the app will
  6. //! render the error message as just a string.
  7. use dioxus::{dioxus_core::CapturedError, prelude::*};
  8. fn main() {
  9. launch_desktop(app);
  10. }
  11. fn app() -> Element {
  12. rsx! {
  13. ErrorBoundary {
  14. handle_error: |error: CapturedError| rsx! {
  15. h1 { "An error occurred" }
  16. pre { "{error:#?}" }
  17. },
  18. DemoC { x: 1 }
  19. }
  20. }
  21. }
  22. #[component]
  23. fn DemoC(x: i32) -> Element {
  24. rsx! {
  25. h1 { "Error handler demo" }
  26. button {
  27. onclick: move |_| {
  28. // Create an error
  29. let result: Result<Element, &str> = Err("Error");
  30. // And then call `throw` on it. The `throw` method is given by the `Throw` trait which is automatically
  31. // imported via the prelude.
  32. _ = result.throw();
  33. },
  34. "Click to throw an error"
  35. }
  36. }
  37. }