Skip to content

fix: if we hit a 404 in starlette, raise instead of render a 404#670

Merged
maartenbreddels merged 1 commit intomasterfrom
fix_starlette_raise_instead_of_render
Jun 25, 2024
Merged

fix: if we hit a 404 in starlette, raise instead of render a 404#670
maartenbreddels merged 1 commit intomasterfrom
fix_starlette_raise_instead_of_render

Conversation

@maartenbreddels
Copy link
Copy Markdown
Contributor

@maartenbreddels maartenbreddels commented Jun 6, 2024

This allows middleware or error handlers to catch the 404 and do something custom.

Example:

import solara

clicks = solara.reactive(0)

added = False

def add_exception_handler():
    global added
    print("add_exception_handler", added)
    if not added:
        import solara.server.starlette
        from starlette.responses import HTMLResponse
        async def server_error(request, exc):
            return HTMLResponse(content="My custom 404", status_code=exc.status_code)

        solara.server.starlette.app.add_exception_handler(404, server_error)
        added = True

@solara.component
def Page():
    # add the handler after all the imports are done to avoid a circular import
    add_exception_handler()
    solara.Text("hello world")

This allows middleware or error handlers to catch the 404 and do
something custom.

Example:

```
import solara

clicks = solara.reactive(0)

added = False

def add_exception_handler():
    global added
    print("add_exception_handler", added)
    if not added:
        import solara.server.starlette
        from starlette.responses import HTMLResponse
        async def server_error(request, exc):
            return HTMLResponse(content="My custom 404", status_code=exc.status_code)

        solara.server.starlette.app.add_exception_handler(404, server_error)
        added = True

@solara.component
def Page():

    add_exception_handler()
    solara.Text("hello world")
```
Copy link
Copy Markdown
Collaborator

@iisakkirotko iisakkirotko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great! Should be super useful for everyone using Solara, including us :).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants