Skip to content

Commit

Permalink
refactor(api): add error override to convert HTTPErrors from HTML to …
Browse files Browse the repository at this point in the history
…JSON responses
  • Loading branch information
janaka committed Jun 26, 2024
1 parent 0d8b657 commit d52a190
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion web/api/base_handlers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""Base request handlers."""
import json
from typing import Any, Optional, Self

import docq.manage_organisations as m_orgs
from opentelemetry import trace
from tornado.web import RequestHandler
from tornado.web import HTTPError, RequestHandler

from web.api.models import UserModel
from web.utils.handlers import _default_org_id as get_default_org_id
Expand Down Expand Up @@ -42,6 +43,21 @@ def get_current_user(self: Self) -> UserModel | None:
print("get_current_user() called")
return self._current_user

def write_error(self: Self, status_code: int, **kwargs: Any) -> None:
self.set_header("Content-Type", "application/json")
error_response = {
"reason": "An unexpected error occurred.",
"statusCode": 500,
}
if "exc_info" in kwargs:
exc_type, exc_value, _ = kwargs["exc_info"]
# Customize the response based on exception type
if isinstance(exc_value, HTTPError):
error_response["reason"] = exc_value.reason
error_response["statusCode"] = status_code

self.finish(json.dumps(error_response))

# auth_header = self.request.headers.get("Authorization")
# if not auth_header:
# error_msg = "Missing Authorization header"
Expand Down

0 comments on commit d52a190

Please sign in to comment.