dioxus_core/
error_boundary.rs

1use crate::{
2    global_context::current_scope_id, innerlude::provide_context, use_hook, Element, IntoDynNode,
3    Properties, ScopeId, Template, TemplateAttribute, TemplateNode, VNode,
4};
5use std::{
6    any::{Any, TypeId},
7    backtrace::Backtrace,
8    cell::{Ref, RefCell},
9    error::Error,
10    fmt::{Debug, Display},
11    rc::Rc,
12    str::FromStr,
13};
14
15/// A panic in a component that was caught by an error boundary.
16///
17/// <div class="warning">
18///
19/// WASM currently does not support caching unwinds, so this struct will not be created in WASM.
20///
21/// </div>
22pub struct CapturedPanic {
23    #[allow(dead_code)]
24    /// The error that was caught
25    pub error: Box<dyn Any + 'static>,
26}
27
28impl Debug for CapturedPanic {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("CapturedPanic").finish()
31    }
32}
33
34impl Display for CapturedPanic {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.write_fmt(format_args!("Encountered panic: {:?}", self.error))
37    }
38}
39
40impl Error for CapturedPanic {}
41
42/// Provide an error boundary to catch errors from child components
43pub fn provide_error_boundary() -> ErrorContext {
44    provide_context(ErrorContext::new(
45        Vec::new(),
46        current_scope_id().unwrap_or_else(|e| panic!("{}", e)),
47    ))
48}
49
50/// A trait for any type that can be downcast to a concrete type and implements Debug. This is automatically implemented for all types that implement Any + Debug.
51pub trait AnyError {
52    fn as_any(&self) -> &dyn Any;
53    fn as_error(&self) -> &dyn Error;
54}
55
56/// An wrapper error type for types that only implement Display. We use a inner type here to avoid overlapping implementations for DisplayError and impl Error
57struct DisplayError(DisplayErrorInner);
58
59impl<E: Display + 'static> From<E> for DisplayError {
60    fn from(e: E) -> Self {
61        Self(DisplayErrorInner(Box::new(e)))
62    }
63}
64
65struct DisplayErrorInner(Box<dyn Display>);
66impl Display for DisplayErrorInner {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        self.0.fmt(f)
69    }
70}
71
72impl Debug for DisplayErrorInner {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        self.0.fmt(f)
75    }
76}
77
78impl Error for DisplayErrorInner {}
79
80impl AnyError for DisplayError {
81    fn as_any(&self) -> &dyn Any {
82        &self.0 .0
83    }
84
85    fn as_error(&self) -> &dyn Error {
86        &self.0
87    }
88}
89
90/// Provides context methods to [`Result`] and [`Option`] types that are compatible with [`CapturedError`]
91///
92/// This trait is sealed and cannot be implemented outside of dioxus-core
93pub trait Context<T, E>: private::Sealed {
94    /// Add a visual representation of the error that the [`ErrorBoundary`] may render
95    ///
96    /// # Example
97    /// ```rust
98    /// # use dioxus::prelude::*;
99    /// fn Component() -> Element {
100    ///     // You can bubble up errors with `?` inside components, and event handlers
101    ///     // Along with the error itself, you can provide a way to display the error by calling `show`
102    ///     let number = "1234".parse::<usize>().show(|error| rsx! {
103    ///         div {
104    ///             background_color: "red",
105    ///             color: "white",
106    ///             "Error parsing number: {error}"
107    ///         }
108    ///     })?;
109    ///     unimplemented!()
110    /// }
111    /// ```
112    fn show(self, display_error: impl FnOnce(&E) -> Element) -> Result<T>;
113
114    /// Wrap the result additional context about the error that occurred.
115    ///
116    /// # Example
117    /// ```rust
118    /// # use dioxus::prelude::*;
119    /// fn NumberParser() -> Element {
120    ///     // You can bubble up errors with `?` inside components, and event handlers
121    ///     // Along with the error itself, you can provide a way to display the error by calling `context`
122    ///     let number = "-1234".parse::<usize>().context("Parsing number inside of the NumberParser")?;
123    ///     unimplemented!()
124    /// }
125    /// ```
126    fn context<C: Display + 'static>(self, context: C) -> Result<T>;
127
128    /// Wrap the result with additional context about the error that occurred. The closure will only be run if the Result is an error.
129    ///
130    /// # Example
131    /// ```rust
132    /// # use dioxus::prelude::*;
133    /// fn NumberParser() -> Element {
134    ///     // You can bubble up errors with `?` inside components, and event handlers
135    ///     // Along with the error itself, you can provide a way to display the error by calling `context`
136    ///     let number = "-1234".parse::<usize>().with_context(|| format!("Timestamp: {:?}", std::time::Instant::now()))?;
137    ///     unimplemented!()
138    /// }
139    /// ```
140    fn with_context<C: Display + 'static>(self, context: impl FnOnce() -> C) -> Result<T>;
141}
142
143impl<T, E> Context<T, E> for std::result::Result<T, E>
144where
145    E: Error + 'static,
146{
147    fn show(self, display_error: impl FnOnce(&E) -> Element) -> Result<T> {
148        // We don't use result mapping to avoid extra frames
149        match self {
150            std::result::Result::Ok(value) => Ok(value),
151            Err(error) => {
152                let render = display_error(&error).unwrap_or_default();
153                let mut error: CapturedError = error.into();
154                error.render = render;
155                Err(error)
156            }
157        }
158    }
159
160    fn context<C: Display + 'static>(self, context: C) -> Result<T> {
161        self.with_context(|| context)
162    }
163
164    fn with_context<C: Display + 'static>(self, context: impl FnOnce() -> C) -> Result<T> {
165        // We don't use result mapping to avoid extra frames
166        match self {
167            std::result::Result::Ok(value) => Ok(value),
168            Err(error) => {
169                let mut error: CapturedError = error.into();
170                error.context.push(Rc::new(AdditionalErrorContext {
171                    backtrace: Backtrace::capture(),
172                    context: Box::new(context()),
173                    scope: current_scope_id().ok(),
174                }));
175                Err(error)
176            }
177        }
178    }
179}
180
181impl<T> Context<T, CapturedError> for Option<T> {
182    fn show(self, display_error: impl FnOnce(&CapturedError) -> Element) -> Result<T> {
183        // We don't use result mapping to avoid extra frames
184        match self {
185            Some(value) => Ok(value),
186            None => {
187                let mut error = CapturedError::from_display("Value was none");
188                let render = display_error(&error).unwrap_or_default();
189                error.render = render;
190                Err(error)
191            }
192        }
193    }
194
195    fn context<C: Display + 'static>(self, context: C) -> Result<T> {
196        self.with_context(|| context)
197    }
198
199    fn with_context<C: Display + 'static>(self, context: impl FnOnce() -> C) -> Result<T> {
200        // We don't use result mapping to avoid extra frames
201        match self {
202            Some(value) => Ok(value),
203            None => {
204                let error = CapturedError::from_display(context());
205                Err(error)
206            }
207        }
208    }
209}
210
211pub(crate) mod private {
212    use super::*;
213
214    pub trait Sealed {}
215
216    impl<T, E> Sealed for std::result::Result<T, E> where E: Error {}
217    impl<T> Sealed for Option<T> {}
218}
219
220impl<T: Any + Error> AnyError for T {
221    fn as_any(&self) -> &dyn Any {
222        self
223    }
224
225    fn as_error(&self) -> &dyn Error {
226        self
227    }
228}
229
230/// A context with information about suspended components
231#[derive(Debug, Clone)]
232pub struct ErrorContext {
233    errors: Rc<RefCell<Vec<CapturedError>>>,
234    id: ScopeId,
235}
236
237impl PartialEq for ErrorContext {
238    fn eq(&self, other: &Self) -> bool {
239        Rc::ptr_eq(&self.errors, &other.errors)
240    }
241}
242
243impl ErrorContext {
244    /// Create a new suspense boundary in a specific scope
245    pub(crate) fn new(errors: Vec<CapturedError>, id: ScopeId) -> Self {
246        Self {
247            errors: Rc::new(RefCell::new(errors)),
248            id,
249        }
250    }
251
252    /// Get all errors thrown from child components
253    pub fn errors(&self) -> Ref<[CapturedError]> {
254        Ref::map(self.errors.borrow(), |errors| errors.as_slice())
255    }
256
257    /// Get the Element from the first error that can be shown
258    pub fn show(&self) -> Option<Element> {
259        self.errors.borrow().iter().find_map(|task| task.show())
260    }
261
262    /// Push an error into this Error Boundary
263    pub fn insert_error(&self, error: CapturedError) {
264        self.errors.borrow_mut().push(error);
265        self.id.needs_update();
266    }
267
268    /// Clear all errors from this Error Boundary
269    pub fn clear_errors(&self) {
270        self.errors.borrow_mut().clear();
271    }
272}
273
274/// Errors can have additional context added as they bubble up the render tree
275/// This context can be used to provide additional information to the user
276struct AdditionalErrorContext {
277    backtrace: Backtrace,
278    context: Box<dyn Display>,
279    scope: Option<ScopeId>,
280}
281
282impl Debug for AdditionalErrorContext {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.debug_struct("ErrorContext")
285            .field("backtrace", &self.backtrace)
286            .field("context", &self.context.to_string())
287            .finish()
288    }
289}
290
291impl Display for AdditionalErrorContext {
292    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
293        let AdditionalErrorContext {
294            backtrace,
295            context,
296            scope,
297        } = self;
298
299        write!(f, "{context} (from ")?;
300
301        if let Some(scope) = scope {
302            write!(f, "scope {scope:?} ")?;
303        }
304
305        write!(f, "at {backtrace:?})")
306    }
307}
308
309/// A type alias for a result that can be either a boxed error or a value
310/// This is useful to avoid having to use `Result<T, CapturedError>` everywhere
311pub type Result<T = ()> = std::result::Result<T, CapturedError>;
312
313/// A helper function for an Ok result that can be either a boxed error or a value
314/// This is useful to avoid having to use `Ok<T, CapturedError>` everywhere
315#[allow(non_snake_case)]
316pub fn Ok<T>(value: T) -> Result<T> {
317    Result::Ok(value)
318}
319
320#[derive(Clone)]
321/// An instance of an error captured by a descendant component.
322pub struct CapturedError {
323    /// The error captured by the error boundary
324    error: Rc<dyn AnyError + 'static>,
325
326    /// The backtrace of the error
327    backtrace: Rc<Backtrace>,
328
329    /// The scope that threw the error
330    scope: ScopeId,
331
332    /// An error message that can be displayed to the user
333    pub(crate) render: VNode,
334
335    /// Additional context that was added to the error
336    context: Vec<Rc<AdditionalErrorContext>>,
337}
338
339impl FromStr for CapturedError {
340    type Err = std::convert::Infallible;
341
342    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
343        std::result::Result::Ok(Self::from_display(s.to_string()))
344    }
345}
346
347#[cfg(feature = "serialize")]
348#[derive(serde::Serialize, serde::Deserialize)]
349struct SerializedCapturedError {
350    error: String,
351    context: Vec<String>,
352}
353
354#[cfg(feature = "serialize")]
355impl serde::Serialize for CapturedError {
356    fn serialize<S: serde::Serializer>(
357        &self,
358        serializer: S,
359    ) -> std::result::Result<S::Ok, S::Error> {
360        let serialized = SerializedCapturedError {
361            error: self.error.as_error().to_string(),
362            context: self
363                .context
364                .iter()
365                .map(|context| context.to_string())
366                .collect(),
367        };
368        serialized.serialize(serializer)
369    }
370}
371
372#[cfg(feature = "serialize")]
373impl<'de> serde::Deserialize<'de> for CapturedError {
374    fn deserialize<D: serde::Deserializer<'de>>(
375        deserializer: D,
376    ) -> std::result::Result<Self, D::Error> {
377        let serialized = SerializedCapturedError::deserialize(deserializer)?;
378
379        let error = DisplayError::from(serialized.error);
380        let context = serialized
381            .context
382            .into_iter()
383            .map(|context| {
384                Rc::new(AdditionalErrorContext {
385                    scope: None,
386                    backtrace: Backtrace::disabled(),
387                    context: Box::new(context),
388                })
389            })
390            .collect();
391
392        std::result::Result::Ok(Self {
393            error: Rc::new(error),
394            context,
395            backtrace: Rc::new(Backtrace::disabled()),
396            scope: ScopeId::ROOT,
397            render: VNode::placeholder(),
398        })
399    }
400}
401
402impl Debug for CapturedError {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        f.debug_struct("CapturedError")
405            .field("error", &self.error.as_error())
406            .field("backtrace", &self.backtrace)
407            .field("scope", &self.scope)
408            .finish()
409    }
410}
411
412impl<E: AnyError + 'static> From<E> for CapturedError {
413    fn from(error: E) -> Self {
414        Self {
415            error: Rc::new(error),
416            backtrace: Rc::new(Backtrace::capture()),
417            scope: current_scope_id()
418                .expect("Cannot create an error boundary outside of a component's scope."),
419            render: Default::default(),
420            context: Default::default(),
421        }
422    }
423}
424
425impl CapturedError {
426    /// Create a new captured error
427    pub fn new(error: impl AnyError + 'static) -> Self {
428        Self {
429            error: Rc::new(error),
430            backtrace: Rc::new(Backtrace::capture()),
431            scope: current_scope_id().unwrap_or(ScopeId::ROOT),
432            render: Default::default(),
433            context: Default::default(),
434        }
435    }
436
437    /// Create a new error from a type that only implements [`Display`]. If your type implements [`Error`], you can use [`CapturedError::from`] instead.
438    pub fn from_display(error: impl Display + 'static) -> Self {
439        Self {
440            error: Rc::new(DisplayError::from(error)),
441            backtrace: Rc::new(Backtrace::capture()),
442            scope: current_scope_id().unwrap_or(ScopeId::ROOT),
443            render: Default::default(),
444            context: Default::default(),
445        }
446    }
447
448    /// Mark the error as being thrown from a specific scope
449    pub fn with_origin(mut self, scope: ScopeId) -> Self {
450        self.scope = scope;
451        self
452    }
453
454    /// Get a VNode representation of the error if the error provides one
455    pub fn show(&self) -> Option<Element> {
456        if self.render == VNode::placeholder() {
457            None
458        } else {
459            Some(std::result::Result::Ok(self.render.clone()))
460        }
461    }
462
463    /// Create a deep clone of this error
464    pub(crate) fn deep_clone(&self) -> Self {
465        Self {
466            render: self.render.deep_clone(),
467            ..self.clone()
468        }
469    }
470}
471
472impl PartialEq for CapturedError {
473    fn eq(&self, other: &Self) -> bool {
474        format!("{:?}", self) == format!("{:?}", other)
475    }
476}
477
478impl Display for CapturedError {
479    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480        f.write_fmt(format_args!(
481            "Encountered error: {:?}\nIn scope: {:?}\nBacktrace: {}\nContext: ",
482            self.error.as_error(),
483            self.scope,
484            self.backtrace
485        ))?;
486        for context in &*self.context {
487            f.write_fmt(format_args!("{}\n", context))?;
488        }
489        std::result::Result::Ok(())
490    }
491}
492
493impl CapturedError {
494    /// Downcast the error type into a concrete error type
495    pub fn downcast<T: 'static>(&self) -> Option<&T> {
496        if TypeId::of::<T>() == (*self.error).type_id() {
497            self.error.as_any().downcast_ref::<T>()
498        } else {
499            None
500        }
501    }
502}
503
504pub(crate) fn throw_into(error: impl Into<CapturedError>, scope: ScopeId) {
505    let error = error.into();
506    if let Some(cx) = scope.consume_context::<ErrorContext>() {
507        cx.insert_error(error)
508    } else {
509        tracing::error!(
510            "Tried to throw an error into an error boundary, but failed to locate a boundary: {:?}",
511            error
512        )
513    }
514}
515
516#[allow(clippy::type_complexity)]
517#[derive(Clone)]
518pub struct ErrorHandler(Rc<dyn Fn(ErrorContext) -> Element>);
519impl<F: Fn(ErrorContext) -> Element + 'static> From<F> for ErrorHandler {
520    fn from(value: F) -> Self {
521        Self(Rc::new(value))
522    }
523}
524
525fn default_handler(errors: ErrorContext) -> Element {
526    static TEMPLATE: Template = Template {
527        roots: &[TemplateNode::Element {
528            tag: "div",
529            namespace: None,
530            attrs: &[TemplateAttribute::Static {
531                name: "color",
532                namespace: Some("style"),
533                value: "red",
534            }],
535            children: &[TemplateNode::Dynamic { id: 0usize }],
536        }],
537        node_paths: &[&[0u8, 0u8]],
538        attr_paths: &[],
539    };
540    std::result::Result::Ok(VNode::new(
541        None,
542        TEMPLATE,
543        Box::new([errors
544            .errors()
545            .iter()
546            .map(|e| {
547                static TEMPLATE: Template = Template {
548                    roots: &[TemplateNode::Element {
549                        tag: "pre",
550                        namespace: None,
551                        attrs: &[],
552                        children: &[TemplateNode::Dynamic { id: 0usize }],
553                    }],
554                    node_paths: &[&[0u8, 0u8]],
555                    attr_paths: &[],
556                };
557                VNode::new(
558                    None,
559                    TEMPLATE,
560                    Box::new([e.to_string().into_dyn_node()]),
561                    Default::default(),
562                )
563            })
564            .into_dyn_node()]),
565        Default::default(),
566    ))
567}
568
569#[derive(Clone)]
570pub struct ErrorBoundaryProps {
571    children: Element,
572    handle_error: ErrorHandler,
573}
574impl ErrorBoundaryProps {
575    /**
576    Create a builder for building `ErrorBoundaryProps`.
577    On the builder, call `.children(...)`(optional), `.handle_error(...)`(optional) to set the values of the fields.
578    Finally, call `.build()` to create the instance of `ErrorBoundaryProps`.
579                        */
580    #[allow(dead_code)]
581    pub fn builder() -> ErrorBoundaryPropsBuilder<((), ())> {
582        ErrorBoundaryPropsBuilder { fields: ((), ()) }
583    }
584}
585#[must_use]
586#[doc(hidden)]
587#[allow(dead_code, non_camel_case_types, non_snake_case)]
588pub struct ErrorBoundaryPropsBuilder<TypedBuilderFields> {
589    fields: TypedBuilderFields,
590}
591impl<TypedBuilderFields> Clone for ErrorBoundaryPropsBuilder<TypedBuilderFields>
592where
593    TypedBuilderFields: Clone,
594{
595    fn clone(&self) -> Self {
596        Self {
597            fields: self.fields.clone(),
598        }
599    }
600}
601impl Properties for ErrorBoundaryProps {
602    type Builder = ErrorBoundaryPropsBuilder<((), ())>;
603    fn builder() -> Self::Builder {
604        ErrorBoundaryProps::builder()
605    }
606    fn memoize(&mut self, other: &Self) -> bool {
607        *self = other.clone();
608        false
609    }
610}
611#[doc(hidden)]
612#[allow(dead_code, non_camel_case_types, non_snake_case)]
613pub trait ErrorBoundaryPropsBuilder_Optional<T> {
614    fn into_value<F: FnOnce() -> T>(self, default: F) -> T;
615}
616impl<T> ErrorBoundaryPropsBuilder_Optional<T> for () {
617    fn into_value<F: FnOnce() -> T>(self, default: F) -> T {
618        default()
619    }
620}
621impl<T> ErrorBoundaryPropsBuilder_Optional<T> for (T,) {
622    fn into_value<F: FnOnce() -> T>(self, _: F) -> T {
623        self.0
624    }
625}
626#[allow(dead_code, non_camel_case_types, missing_docs)]
627impl<__handle_error> ErrorBoundaryPropsBuilder<((), __handle_error)> {
628    pub fn children(
629        self,
630        children: Element,
631    ) -> ErrorBoundaryPropsBuilder<((Element,), __handle_error)> {
632        let children = (children,);
633        let (_, handle_error) = self.fields;
634        ErrorBoundaryPropsBuilder {
635            fields: (children, handle_error),
636        }
637    }
638}
639#[doc(hidden)]
640#[allow(dead_code, non_camel_case_types, non_snake_case)]
641pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_children {}
642#[doc(hidden)]
643#[allow(dead_code, non_camel_case_types, missing_docs)]
644impl<__handle_error> ErrorBoundaryPropsBuilder<((Element,), __handle_error)> {
645    #[deprecated(note = "Repeated field children")]
646    pub fn children(
647        self,
648        _: ErrorBoundaryPropsBuilder_Error_Repeated_field_children,
649    ) -> ErrorBoundaryPropsBuilder<((Element,), __handle_error)> {
650        self
651    }
652}
653#[allow(dead_code, non_camel_case_types, missing_docs)]
654impl<__children> ErrorBoundaryPropsBuilder<(__children, ())> {
655    pub fn handle_error(
656        self,
657        handle_error: impl ::core::convert::Into<ErrorHandler>,
658    ) -> ErrorBoundaryPropsBuilder<(__children, (ErrorHandler,))> {
659        let handle_error = (handle_error.into(),);
660        let (children, _) = self.fields;
661        ErrorBoundaryPropsBuilder {
662            fields: (children, handle_error),
663        }
664    }
665}
666#[doc(hidden)]
667#[allow(dead_code, non_camel_case_types, non_snake_case)]
668pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error {}
669#[doc(hidden)]
670#[allow(dead_code, non_camel_case_types, missing_docs)]
671impl<__children> ErrorBoundaryPropsBuilder<(__children, (ErrorHandler,))> {
672    #[deprecated(note = "Repeated field handle_error")]
673    pub fn handle_error(
674        self,
675        _: ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error,
676    ) -> ErrorBoundaryPropsBuilder<(__children, (ErrorHandler,))> {
677        self
678    }
679}
680#[allow(dead_code, non_camel_case_types, missing_docs)]
681impl<
682        __handle_error: ErrorBoundaryPropsBuilder_Optional<ErrorHandler>,
683        __children: ErrorBoundaryPropsBuilder_Optional<Element>,
684    > ErrorBoundaryPropsBuilder<(__children, __handle_error)>
685{
686    pub fn build(self) -> ErrorBoundaryProps {
687        let (children, handle_error) = self.fields;
688        let children = ErrorBoundaryPropsBuilder_Optional::into_value(children, VNode::empty);
689        let handle_error = ErrorBoundaryPropsBuilder_Optional::into_value(handle_error, || {
690            ErrorHandler(Rc::new(default_handler))
691        });
692        ErrorBoundaryProps {
693            children,
694            handle_error,
695        }
696    }
697}
698
699/// Create a new error boundary component that catches any errors thrown from child components
700///
701/// ## Details
702///
703/// Error boundaries handle errors within a specific part of your application. Any errors passed up from a child will be caught by the nearest error boundary.
704///
705/// ## Example
706///
707/// ```rust, no_run
708/// # use dioxus::prelude::*;
709/// fn App() -> Element {
710///     rsx! {
711///         ErrorBoundary {
712///             handle_error: |errors: ErrorContext| rsx! { "Oops, we encountered an error. Please report {errors:?} to the developer of this application" },
713///             Counter {
714///                 multiplier: "1234"
715///             }
716///         }
717///     }
718/// }
719///
720/// #[component]
721/// fn Counter(multiplier: String) -> Element {
722///     // You can bubble up errors with `?` inside components
723///     let multiplier_parsed = multiplier.parse::<usize>()?;
724///     let mut count = use_signal(|| multiplier_parsed);
725///     rsx! {
726///         button {
727///             // Or inside event handlers
728///             onclick: move |_| {
729///                 let multiplier_parsed = multiplier.parse::<usize>()?;
730///                 *count.write() *= multiplier_parsed;
731///                 Ok(())
732///             },
733///             "{count}x{multiplier}"
734///         }
735///     }
736/// }
737/// ```
738///
739/// ## Usage
740///
741/// Error boundaries are an easy way to handle errors in your application.
742/// They are similar to `try/catch` in JavaScript, but they only catch errors in the tree below them.
743/// Error boundaries are quick to implement, but it can be useful to individually handle errors in your components to provide a better user experience when you know that an error is likely to occur.
744#[allow(non_upper_case_globals, non_snake_case)]
745pub fn ErrorBoundary(props: ErrorBoundaryProps) -> Element {
746    let error_boundary = use_hook(provide_error_boundary);
747    let errors = error_boundary.errors();
748    if errors.is_empty() {
749        std::result::Result::Ok({
750            static TEMPLATE: Template = Template {
751                roots: &[TemplateNode::Dynamic { id: 0usize }],
752                node_paths: &[&[0u8]],
753                attr_paths: &[],
754            };
755            VNode::new(
756                None,
757                TEMPLATE,
758                Box::new([(props.children).into_dyn_node()]),
759                Default::default(),
760            )
761        })
762    } else {
763        tracing::trace!("scope id: {:?}", current_scope_id());
764        tracing::trace!("handling errors: {:?}", errors);
765        (props.handle_error.0)(error_boundary.clone())
766    }
767}