Skip to content
This repository has been archived by the owner on Dec 26, 2023. It is now read-only.

Commit

Permalink
feat: return all exceptions in JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
morenocantoj committed Aug 31, 2022
1 parent 59cccc6 commit 8770962
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ __pycache__
.env

# Instance
instance
instance

# IDE
.vscode
Empty file added src/api/shared/__init__.py
Empty file.
23 changes: 23 additions & 0 deletions src/api/shared/handle_http_exception.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
This module handlers all exceptions regarding HTTP error codes
"""

from flask import json, Blueprint
from werkzeug.exceptions import HTTPException

errors_bp = Blueprint('errors', __name__)


@errors_bp.app_errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return response
3 changes: 3 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ def create_app():
from .api.health.health_controller import health_bp
app.register_blueprint(health_bp)

from .api.shared.handle_http_exception import errors_bp
app.register_blueprint(errors_bp)

# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
Expand Down

0 comments on commit 8770962

Please sign in to comment.