web_error
is a set of exceptions and handlers for use in web apis to support easy error management and responses
Each exception easily marshals to JSON for use in api errors. Handlers for different web frameworks are provided.
The base web_error.error.HttpException
accepts a message
, debug_message
, code
and status
(default 500)
And will render a response with status as the status code:
{
"code": "code",
"message": "message",
"debug_message": "debug_message",
}
Some convenience Exceptions are provided, to create custom error subclass these
and define message
and code
attributes.
web_error.error.ServerException
provides status 500 errorsweb_error.error.BadRequestException
provides status 400 errorsweb_error.error.UnauthorisedException
provides status 401 errorsweb_error.error.NotFoundException
provides status 404 errors
Subclassing the convenience classes provide a simple way to consistently raise the same error and message.
Code is an optional attribute to provide a unique value to parse in a frontend/client instead of matching against messages.
from web_error.error import NotFoundException
class UserNotFoundError(NotFoundException):
message = "User not found."
code = "E001"
Include the exception_handler
in your app.
exception_handler = web_error.handler.fastapi.exception_handler
return FastAPI(
exception_handlers={
Exception: exception_handler,
RequestValidationError: exception_handler,
HTTPException: exception_handler,
},
)
Include the pyramid exception handlers in your config.
def main(global_config, **config_blob):
config = Configurator(settings=config_blob)
...
config.scan("web_error.handler.pyramid")
return config.make_wsgi_app()
This will handle all unexpected errors, and any app specific errors.
@view_config(route_name="test", renderer="json")
def test(request):
raise UserNotFoundError("debug message")
Register the error handler with your application
app.register_error_handler(Exception, web_error.handler.flask.exception_handler)
Decorate your views with the error handler.
@web_error.handler.aiohttp.view_error_handler
async def user(self):
raise UserNotFoundError("debug message")