mirror of
https://github.com/django-components/django-components.git
synced 2025-11-18 06:06:14 +00:00
refactor: add ErrorFallback (#1433)
This commit is contained in:
parent
eee3910b54
commit
60651f30b2
10 changed files with 603 additions and 11 deletions
|
|
@ -85,7 +85,7 @@ from django_components.util.routing import URLRoute, URLRouteHandler
|
|||
from django_components.util.types import Empty
|
||||
|
||||
# NOTE: Import built-in components last to avoid circular imports
|
||||
from django_components.components import DynamicComponent
|
||||
from django_components.components import DynamicComponent, ErrorFallback
|
||||
|
||||
# isort: on
|
||||
|
||||
|
|
@ -120,6 +120,7 @@ __all__ = [
|
|||
"DependenciesStrategy",
|
||||
"DynamicComponent",
|
||||
"Empty",
|
||||
"ErrorFallback",
|
||||
"ExtensionComponentConfig",
|
||||
"FillNode",
|
||||
"NotRegistered",
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ class ComponentsConfig(AppConfig):
|
|||
from django_components.autodiscovery import autodiscover, import_libraries
|
||||
from django_components.component_registry import registry
|
||||
from django_components.components.dynamic import DynamicComponent
|
||||
from django_components.components.error_fallback import ErrorFallback
|
||||
from django_components.extension import extensions
|
||||
from django_components.util.django_monkeypatch import (
|
||||
monkeypatch_include_node,
|
||||
|
|
@ -66,6 +67,7 @@ class ComponentsConfig(AppConfig):
|
|||
|
||||
# Register the dynamic component under the name as given in settings
|
||||
registry.register(app_settings.DYNAMIC_COMPONENT_NAME, DynamicComponent)
|
||||
registry.register("error_fallback", ErrorFallback)
|
||||
|
||||
# Let extensions process any components which may have been created before the app was ready
|
||||
extensions._init_app()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
# NOTE: Components exported here are documented in the API reference
|
||||
from django_components.components.dynamic import DynamicComponent
|
||||
from django_components.components.error_fallback import ErrorFallback
|
||||
|
||||
__all__ = ["DynamicComponent"]
|
||||
__all__ = ["DynamicComponent", "ErrorFallback"]
|
||||
|
|
|
|||
156
src/django_components/components/error_fallback.py
Normal file
156
src/django_components/components/error_fallback.py
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
from typing import NamedTuple, Optional, cast
|
||||
|
||||
from django.template import Context, Template
|
||||
from django.template.exceptions import TemplateSyntaxError
|
||||
|
||||
from django_components import Component, OnRenderGenerator, SlotInput, types
|
||||
|
||||
|
||||
class ErrorFallback(Component):
|
||||
"""
|
||||
Use `ErrorFallback` to catch errors and display a fallback content instead.
|
||||
|
||||
This is similar to React's
|
||||
[`ErrorBoundary`](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
|
||||
component.
|
||||
|
||||
**Example:**
|
||||
|
||||
Given this template:
|
||||
|
||||
```django
|
||||
{% component "error_fallback" fallback="Oops, something went wrong" %}
|
||||
{% component "table" / %}
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
- If the `table` component does NOT raise an error, then the table is rendered as normal.
|
||||
- If the `table` component DOES raise an error, then `error_fallback` renders `Oops, something went wrong`.
|
||||
|
||||
To have more control over the fallback content, you can use the `fallback` slot
|
||||
instead of the `fallback` kwarg.
|
||||
|
||||
```django
|
||||
{% component "error_fallback" %}
|
||||
{% fill "content" %}
|
||||
{% component "table" / %}
|
||||
{% endfill %}
|
||||
{% fill "fallback" %}
|
||||
<p>Oops, something went wrong</p>
|
||||
{% button href="/report-error" %}
|
||||
Report error
|
||||
{% endbutton %}
|
||||
{% endfill %}
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
If you want to print the error, you can access the `error` variable
|
||||
as [slot data](../../concepts/fundamentals/slots/#slot-data).
|
||||
|
||||
```django
|
||||
{% component "error_fallback" %}
|
||||
{% fill "content" %}
|
||||
{% component "table" / %}
|
||||
{% endfill %}
|
||||
{% fill "fallback" data="data" %}
|
||||
Oops, something went wrong:
|
||||
<pre>{{ data.error }}</pre>
|
||||
{% endfill %}
|
||||
{% endcomponent %}
|
||||
```
|
||||
|
||||
**Python:**
|
||||
|
||||
With fallback kwarg:
|
||||
|
||||
```py
|
||||
from django_components import ErrorFallback
|
||||
|
||||
ErrorFallback.render(
|
||||
slots={
|
||||
# Main content
|
||||
"content": lambda ctx: TableComponent.render(
|
||||
deps_strategy="ignore",
|
||||
),
|
||||
},
|
||||
kwargs={
|
||||
# Fallback content
|
||||
"fallback": "Oops, something went wrong",
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
With fallback slot:
|
||||
|
||||
```py
|
||||
from django_components import ErrorFallback
|
||||
|
||||
ErrorFallback.render(
|
||||
slots={
|
||||
# Main content
|
||||
"content": lambda ctx: TableComponent.render(
|
||||
deps_strategy="ignore",
|
||||
),
|
||||
# Fallback content
|
||||
"fallback": lambda ctx: mark_safe("Oops, something went wrong: " + ctx.error),
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
!!! info
|
||||
|
||||
Remember to define the `content` slot as function, so it's evaluated from inside of `ErrorFallback`.
|
||||
"""
|
||||
|
||||
class Kwargs(NamedTuple):
|
||||
fallback: Optional[str] = None
|
||||
|
||||
class Slots(NamedTuple):
|
||||
default: Optional[SlotInput] = None
|
||||
content: Optional[SlotInput] = None
|
||||
fallback: Optional[SlotInput] = None
|
||||
|
||||
def on_render(
|
||||
self,
|
||||
context: Context,
|
||||
template: Optional[Template],
|
||||
) -> OnRenderGenerator:
|
||||
if template is None:
|
||||
raise TemplateSyntaxError("The 'error_fallback' component must have a template.")
|
||||
|
||||
fallback_kwarg = cast("ErrorFallback.Kwargs", self.kwargs).fallback
|
||||
fallback_slot = cast("ErrorFallback.Slots", self.slots).fallback
|
||||
|
||||
if fallback_kwarg is not None and fallback_slot is not None:
|
||||
raise TemplateSyntaxError(
|
||||
"The 'fallback' argument and slot cannot both be provided. Please provide only one.",
|
||||
)
|
||||
|
||||
result, error = yield lambda: template.render(context)
|
||||
|
||||
# No error, return the result
|
||||
if error is None:
|
||||
return result
|
||||
|
||||
# Error, return the fallback
|
||||
if fallback_kwarg is not None:
|
||||
return fallback_kwarg
|
||||
elif fallback_slot is not None:
|
||||
# Render the template second time, this time with the error
|
||||
# So that we render the fallback slot with proper access to the outer context and whatnot.
|
||||
with context.push({"error": error}):
|
||||
return template.render(context)
|
||||
else:
|
||||
return ""
|
||||
|
||||
# TODO - Once we don't have to pass Context to the slot, we can remove the template
|
||||
# and render the slots directly.
|
||||
template: types.django_html = """
|
||||
{% if not error %}
|
||||
{% slot "content" default / %}
|
||||
{% else %}
|
||||
{% slot "fallback" error=error / %}
|
||||
{% endif %}
|
||||
"""
|
||||
Loading…
Add table
Add a link
Reference in a new issue