BlackSheep icon indicating copy to clipboard operation
BlackSheep copied to clipboard

Allow overriding default exception handler for Unhandled Exception

Open YassineElbouchaibi opened this issue 3 years ago • 1 comments

🚀 Feature Request

Allow overriding default exception handler for Unhandled Exception.

Implementation suggestion :

https://github.com/Neoteroi/BlackSheep/blob/main/blacksheep/baseapp.pyx#L132

Could be done by looking for something like 500 or "DEFAULT" in the exceptions_handlers. If these keys (or the key that will be chosen) don't resolve to a handler then use the framework's default handler.

Edit:

I just realized, the default handle_internal_server_error can be monkey patched, so there is obviously a workaround to this.

from blacksheep import Request, Response
from blacksheep.server import Application

async def handle_internal_server_error(
    app: Application,
    request: Request,
    exception: Exception,
) -> Response:
    ...


def configure_internal_server_error_handler() -> None:
    Application.handle_internal_server_error = handle_internal_server_error  # type: ignore

YassineElbouchaibi avatar Jul 18 '21 14:07 YassineElbouchaibi

Hi @YassineElbouchaibi, thanks for your very good recommendation. I plan to include this feature soon with the next release. 😄

RobertoPrevato avatar Jul 19 '21 08:07 RobertoPrevato

Closing this issue, as it is indeed sufficient to define a custom Application class.

from blacksheep import Application, json
from blacksheep.messages import Request


class MyApp(Application):
    async def handle_internal_server_error(self, request: Request, exc: Exception):
        return json({"message": "Oh, no!"}, 500)

RobertoPrevato avatar Jul 15 '23 15:07 RobertoPrevato