diff options
author | Frederick Muriuki Muriithi | 2025-07-31 12:56:50 -0500 |
---|---|---|
committer | Frederick Muriuki Muriithi | 2025-07-31 12:59:06 -0500 |
commit | 13fc23d55ff5e28a8d98f404144d337f7b2111d7 (patch) | |
tree | 9bdb7855f8bee325d4cf36681e2b3660dd43fe6b | |
parent | 560dd6accc41cce6626c7b1e9341780f26bc0d4c (diff) | |
download | gn-auth-13fc23d55ff5e28a8d98f404144d337f7b2111d7.tar.gz |
Add type-hinting to the top-level exception handler.
-rw-r--r-- | gn_auth/errors/common.py | 43 |
1 files changed, 25 insertions, 18 deletions
diff --git a/gn_auth/errors/common.py b/gn_auth/errors/common.py index b950c8f..8dc0373 100644 --- a/gn_auth/errors/common.py +++ b/gn_auth/errors/common.py @@ -1,8 +1,9 @@ """Common utilities.""" import logging import traceback +from typing import Callable -from flask import request, jsonify, render_template +from flask import request, Response, make_response, render_template logger = logging.getLogger(__name__) @@ -25,27 +26,33 @@ def __status_code__(exc: Exception): return 500 -def build_handler(description: str): +def build_handler(description: str) -> Callable[[Exception], Response]: """Generic utility to build error handlers.""" - def __handler__(exc: Exception): + def __handler__(exc: Exception) -> Response: + """Handle the exception as appropriate for requests of different mimetypes.""" error = (exc.name if hasattr(exc, "name") else exc.__class__.__name__) status_code = __status_code__(exc) content_type = request.content_type if bool(content_type) and content_type.lower() == "application/json": - return ( - jsonify(add_trace(exc, - { - "requested-uri": request.url, - "error": error, - "error_description": description - })), - status_code) - - return (render_template(f"http-error-{str(status_code)[0:-2]}xx.html", - error=exc, - page=request.url, - description=description, - trace=traceback.format_exception(exc)), - status_code) + return make_response(( + add_trace( + exc, + { + "requested-uri": request.url, + "error": error, + "error_description": description + }), + status_code, + {"Content-Type": "application/json"})) + + return make_response(( + render_template( + f"http-error-{str(status_code)[0:-2]}xx.html", + error=exc, + page=request.url, + description=description, + trace=traceback.format_exception(exc)), + status_code, + {"Content-Type": "text/html"})) return __handler__ |