Skip to content

Commit

Permalink
Provide error handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeyklay committed Feb 7, 2023
1 parent ca3cd57 commit 4f6ddae
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions provider/main/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,20 @@
Functions:
handle_error(e) -> Any
bad_request(e) -> Any
page_not_found(e) -> Any
method_not_allowed(e) -> Any
on_json_loading_failed(e: Request, error: json.decoder.JSONDecodeError)
"""

from flask import abort, json
from werkzeug.exceptions import HTTPException
from flask import json, Request
from werkzeug.exceptions import (
HTTPException,
BadRequest,
NotFound,
MethodNotAllowed
)

from provider.main import main

Expand All @@ -31,3 +40,32 @@ def handle_error(e):
})
response.content_type = 'application/json'
return response


@main.app_errorhandler(400)
def bad_request(e):
"""Registers a function to handle 400 errors."""
return handle_error(BadRequest(response=e.get_response()))


@main.app_errorhandler(404)
def page_not_found(e):
"""Registers a function to handle 404 errors."""
return handle_error(NotFound(response=e.get_response()))


@main.app_errorhandler(405)
def method_not_allowed(e):
"""Registers a function to handle 405 errors."""
return handle_error(MethodNotAllowed(response=e.get_response()))


def on_json_loading_failed(req, error):
"""Abort with a custom JSON message."""
raise BadRequest(
description=f'''Failed to decode JSON object: {error}''',
response=req
)


Request.on_json_loading_failed = on_json_loading_failed

0 comments on commit 4f6ddae

Please sign in to comment.