2016-11-16 00:37:40 +00:00
|
|
|
"""
|
|
|
|
Example intercepting uncaught exceptions using Sanic's error handler framework.
|
2017-05-13 15:01:35 +01:00
|
|
|
|
2016-11-16 00:37:40 +00:00
|
|
|
This may be useful for developers wishing to use Sentry, Airbrake, etc.
|
|
|
|
or a custom system to log and monitor unexpected errors in production.
|
2017-05-13 15:01:35 +01:00
|
|
|
|
2016-11-16 00:37:40 +00:00
|
|
|
First we create our own class inheriting from Handler in sanic.exceptions,
|
|
|
|
and pass in an instance of it when we create our Sanic instance. Inside this
|
|
|
|
class' default handler, we can do anything including sending exceptions to
|
|
|
|
an external service.
|
|
|
|
"""
|
2017-03-02 15:55:08 +00:00
|
|
|
from sanic.handlers import ErrorHandler
|
|
|
|
from sanic.exceptions import SanicException
|
2016-11-16 00:37:40 +00:00
|
|
|
"""
|
|
|
|
Imports and code relevant for our CustomHandler class
|
|
|
|
(Ordinarily this would be in a separate file)
|
|
|
|
"""
|
2017-01-20 20:36:15 +00:00
|
|
|
|
2016-11-16 00:37:40 +00:00
|
|
|
|
2017-03-02 15:55:08 +00:00
|
|
|
class CustomHandler(ErrorHandler):
|
2017-01-20 20:36:15 +00:00
|
|
|
|
2016-11-16 00:37:40 +00:00
|
|
|
def default(self, request, exception):
|
|
|
|
# Here, we have access to the exception object
|
|
|
|
# and can do anything with it (log, send to external service, etc)
|
|
|
|
|
|
|
|
# Some exceptions are trivial and built into Sanic (404s, etc)
|
2017-01-27 10:11:29 +00:00
|
|
|
if not isinstance(exception, SanicException):
|
2016-11-16 00:37:40 +00:00
|
|
|
print(exception)
|
|
|
|
|
2016-11-16 12:55:54 +00:00
|
|
|
# Then, we must finish handling the exception by returning
|
|
|
|
# our response to the client
|
|
|
|
# For this we can just call the super class' default handler
|
2017-01-20 20:36:15 +00:00
|
|
|
return super().default(request, exception)
|
2016-11-16 00:37:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
This is an ordinary Sanic server, with the exception that we set the
|
|
|
|
server's error_handler to an instance of our CustomHandler
|
|
|
|
"""
|
|
|
|
|
|
|
|
from sanic import Sanic
|
2017-05-13 15:01:35 +01:00
|
|
|
from sanic.response import json
|
2016-11-16 00:37:40 +00:00
|
|
|
|
|
|
|
app = Sanic(__name__)
|
|
|
|
|
2017-03-02 15:55:08 +00:00
|
|
|
handler = CustomHandler()
|
2016-11-16 00:37:40 +00:00
|
|
|
app.error_handler = handler
|
|
|
|
|
2017-01-20 20:36:15 +00:00
|
|
|
|
2016-11-16 00:37:40 +00:00
|
|
|
@app.route("/")
|
|
|
|
async def test(request):
|
|
|
|
# Here, something occurs which causes an unexpected exception
|
|
|
|
# This exception will flow to our custom handler.
|
2017-01-20 20:36:15 +00:00
|
|
|
1 / 0
|
2017-05-13 15:01:35 +01:00
|
|
|
return json({"test": True})
|
2016-11-16 00:37:40 +00:00
|
|
|
|
|
|
|
|
2017-05-13 15:01:35 +01:00
|
|
|
app.run(host="127.0.0.1", port=8000, debug=True)
|