question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Custom error handler not called by `ServerErrorMiddleware` in debug mode

See original GitHub issue

ServerErrorMiddleware ignores handler argument when app is running in debug mode. Instead, it always calls the default one.

from starlette.applications import Starlette
from starlette.responses import Response

def my_handler(request, exc): 
    if request.app.debug:
        return Response('Fail in debug mode')
    return Response('Fail in production mode')

app = Starlette(
    debug=True,
    exception_handlers={Exception: my_handler}
)

This causes us to do workarounds like reimplementing ServerErrorMiddleware on our own just to use an alternate exception handler in debug mode. Though intuitively, you expect exception_handlers for that purpose.

Would it make sense to always call a configured handler when available, and ignore the default one? A possible solution can look like this:

try:
    await self.app(scope, receive, _send)
except Exception as exc:
    request = Request(scope)
    if self.handler is not None:
        if is_async_callable(self.handler):
            response = await self.handler(request, exc)
        else:
            response = await run_in_threadpool(self.handler, request, exc)
    elif self.debug:
        # In debug mode, return traceback responses.
        response = self.debug_response(request, exc)
    else:
        # Use our default 500 error handler.
        response = self.error_response(request, exc)

Let me know if I can PR it.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:13 (13 by maintainers)

github_iconTop GitHub Comments

1reaction
Kludexcommented, Sep 5, 2022

It doesn’t make sense to me for debug to lose priority. Like, usually you have your handlers, and to debug, you set the parameter.

Right, that was my rationale here too. For comparison, we’ve got equivalent behaviour here to Django’s 500 views and debug behaviour…

docs.djangoproject.com/en/4.0/ref/views/#the-500-server-error-view

Flask has the same behavior as well: https://flask.palletsprojects.com/en/2.2.x/errorhandling/#unhandled-exceptions

Why would Starlette do something different than those two?

1reaction
alex-oleshkevichcommented, Sep 4, 2022

@Kludex I think you can close it. However, I still believe that this is a good add-on to the library. The current implementation steals too much control from the developer.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Custom error handler not called by ServerErrorMiddleware in ...
ServerErrorMiddleware ignores handler argument when app is running in debug mode. Instead, it always calls the default one. from starlette.
Read more >
Express 4 middleware error handler not being called
I want the handler to render a custom error page. app.js var express = require('express') , app = express() , swig ...
Read more >
Error handling in NuxtJS - Damir's Corner
This post is my attempt at creating an overview to use as a reference in the future. Handling Errors. Error handling works differently...
Read more >
Error handling - Apollo GraphQL Docs
When Apollo Server formats an error in a response, it sets the code extension to this value if no other code is set....
Read more >
Handling Errors - FastAPI
Handling Errors¶ · Use HTTPException ¶ · Add custom headers¶ · Install custom exception handlers¶ · Override the default exception handlers¶.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found