about summary refs log tree commit diff
path: root/gn_auth/errors/common.py
blob: b950c8f7cd95d04a17fb790925f9e71512cb1a1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Common utilities."""
import logging
import traceback

from flask import request, jsonify, render_template

logger = logging.getLogger(__name__)


def add_trace(exc: Exception, errobj: dict) -> dict:
    """Add the traceback to the error handling object."""
    return {
        **errobj,
        "error-trace": "".join(traceback.format_exception(exc))
    }

def __status_code__(exc: Exception):
    """Fetch the error code for exceptions that have them."""
    error_code_attributes = (
        "code", "error_code", "errorcode", "status_code", "status_code")
    for attr in error_code_attributes:
        if hasattr(exc, attr):
            return getattr(exc, attr)

    return 500


def build_handler(description: str):
    """Generic utility to build error handlers."""
    def __handler__(exc: Exception):
        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 __handler__