django-components/docs/examples/error_fallback
2025-10-20 21:20:41 +00:00
..
images docs: Add "scenarios" code examples (#1445) 2025-10-08 00:17:31 +02:00
component.py refactor: make it optional having to specify parent class of Args, Kwargs, Slots, etc 2025-10-20 21:20:41 +00:00
page.py docs: Add "scenarios" code examples (#1445) 2025-10-08 00:17:31 +02:00
README.md docs: Add "scenarios" code examples (#1445) 2025-10-08 00:17:31 +02:00
test_example_error_fallback.py docs: Add "scenarios" code examples (#1445) 2025-10-08 00:17:31 +02:00

Error handling

The built-in ErrorFallback component catches errors during component rendering and displays fallback content instead. This is similar to React's ErrorBoundary component.

In this scenario, we have a WeatherWidget component that simulates fetching data from a weather API, which we wrap in the built-in ErrorFallback component.

We have two cases:

  1. API call succeeds. The WeatherWidget component renders the weather information as expected.
  2. API call fails. The ErrorFallback component catches the error and display a user-friendly message instead of breaking the page.
{% component "error_fallback" %}
    {% fill "content" %}
        {% component "weather_widget" location="Atlantis" / %}
    {% endfill %}
    {% fill "fallback" %}
        <p style="color: red;">
            Could not load weather data for <strong>Atlantis</strong>.
            The location may not be supported or the service is temporarily down.
        </p>
    {% endfill %}
{% endcomponent %}

ErrorFallback example

Definition

--8<-- "docs/examples/error_fallback/component.py"

Example

To see the component in action, you can set up a view and URL pattern as shown below.

views.py

--8<-- "docs/examples/error_fallback/page.py"

urls.py

from django.urls import path

from examples.pages.error_fallback import ErrorFallbackPage

urlpatterns = [
    path("examples/error_fallback", ErrorFallbackPage.as_view(), name="error_fallback"),
]