Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fist attempt at a pluggable error reporting #6

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion examples/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,18 @@
from trinket import Trinket, Response
from trinket.response import file_iterator
from trinket.extensions import logger
from trinket.http import HTTPError


bauble = logger(Trinket())
class MyTrinket(Trinket):

async def on_error(self, http_code, message):
if http_code == 404:
message = "This route does not exist, i'm so sorry."
return await super().on_error(http_code, message)


bauble = logger(MyTrinket())


@bauble.route('/')
Expand Down
15 changes: 11 additions & 4 deletions src/trinket/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from autoroutes import Routes

from trinket.handler import request_handler
from trinket.http import HTTPStatus, HTTPError
from trinket.http import HTTPCode, HTTPStatus, HTTPError
from trinket.lifecycle import handler_events
from trinket.proto import Application
from trinket.request import Request
Expand All @@ -25,21 +25,28 @@ def __init__(self):
self.websockets = set()
self.hooks = defaultdict(list)

async def on_error(self, http_code: HTTPCode, message: str=None):
"""This async method allows the customization of errors.
If you need an async log or report or whatever, this is the
place to do it.
"""
raise HTTPError(http_code, message)

async def lookup(self, request: Request):
payload, params = self.routes.match(request.path)

if not payload:
raise HTTPError(HTTPStatus.NOT_FOUND, request.path)
return await self.on_error(404, request.path)

# Uppercased in order to only consider HTTP verbs.
handler = payload.get(request.method.upper(), None)
if handler is None:
raise HTTPError(HTTPStatus.METHOD_NOT_ALLOWED)
return await self.on_error(HTTPStatus.METHOD_NOT_ALLOWED)

# We check if the route is for a websocket handler.
# If it is, we make sure we were asked for an upgrade.
if payload.get('websocket', False) and not request.upgrade:
raise HTTPError(
return await self.on_error(
HTTPStatus.UPGRADE_REQUIRED,
'This is a websocket endpoint, please upgrade.')

Expand Down