sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
505 stars 36 forks source link

Handling Errors Best Practices #52

Closed Filimoa closed 1 year ago

Filimoa commented 1 year ago

What is the best practice when it comes to handling errors with this libary? Should I be wrapping my event generator with a try, except block and return a {event: "error") response? This would be a great addition to the docs and I'll gladly open a pull request.

Here's some example code with the situation in question with fastapi.

async def numbers(minimum: int, maximum: int) -> Any:
    for i in range(minimum, maximum + 1):
        if i == 3:
            raise HTTPException(status=400)
        await asyncio.sleep(0.9)
        yield dict(data=i)

@router.post(
    "/test-sse",
)
async def test_sse(
    request: Request,
) -> Any:
    generator = numbers(1, 5)
    return EventSourceResponse(generator)
sysid commented 1 year ago

I added an example for error handling (examples/error_handling.py).

Not sure if this counts as best practice, though. Do you have other ideas?

sysid commented 1 year ago

I assume the added example is what you were looking for. So I will close the issue.