The Exception Hook is fired when an exception is thrown in an application. Anytime you would normally see the debug view when developing is when this hook will fire. This hook may not be fired if the server does not boot up because of an exception depending on how far into the container the exception is thrown but any normal application exceptions encountered will fire this hook.
The exception hook to tie into is ExceptionHook. This means that the key in the container should end with ExceptionHook and Masonite will call it when the Exception Hook is thrown. We can load things into the container such as:
Notice here that our key ends with ExceptionHook and that we instantiated the object. Let's explore creating this entirly from scratch.
Let's create a class called SentryHook
and put it into app/hooks/sentry.py
.
This should be the basic structure for a hook. All hooks require a load method. This load method will always be passed the application container so it always requires that parameter. From here we can do whatever we need to by making objects from the container.
But for this example we actually don't need the container so we can ignore it.
This should be the finished hook:
Now let's walk through how we can simply tie this into the container so it will be called when an exception is thrown in our project.
We can create a new Service Provider to store our hooks so let's make one.
This will create a new Service Provider inside app/providers/HookProvider.py
that looks like:
Now let's just add our hook to it:
And finally add the Service Provider to our PROVIDERS
constant in our config/application.py
file: