1
0

error_handle.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. ErrorBoundary {
  21. handle_error: |error: CapturedError| rsx! {
  22. h1 { "Another error occurred" }
  23. pre { "{error:#?}" }
  24. },
  25. ComponentPanic {}
  26. }
  27. }
  28. }
  29. #[component]
  30. fn DemoC(x: i32) -> Element {
  31. rsx! {
  32. h1 { "Error handler demo" }
  33. button {
  34. onclick: move |_| {
  35. // Create an error
  36. let result: Result<Element, &str> = Err("Error");
  37. // And then call `throw` on it. The `throw` method is given by the `Throw` trait which is automatically
  38. // imported via the prelude.
  39. _ = result.throw();
  40. },
  41. "Click to throw an error"
  42. }
  43. }
  44. }
  45. #[component]
  46. fn ComponentPanic() -> Element {
  47. panic!("This component panics")
  48. }