from flask import jsonify

from . import main
from ..models import ValidationError


@main.app_errorhandler(ValidationError)
def validatation_error(e):
    return jsonify(error=e.message), 400


def generic_error_handler(e):
    # TODO: log the error
    headers = []
    error = e.description
    if e.code == 401:
        headers = [('WWW-Authenticate', 'Bearer')]
    elif e.code == 500:
        error = "Internal error"

    return jsonify(error=error),  e.code, headers


for code in range(400, 599):
    main.app_errorhandler(code)(generic_error_handler)

from flask import jsonify

from . import main
from ..models import ValidationError


@main.app_errorhandler(ValidationError)
def validatation_error(e):
    return jsonify(error=e.message), 400


def generic_error_handler(e):
    headers = []
    code = getattr(e, 'code', 500)
    error = getattr(e, 'description', 'Internal error')

    if code == 401:
        headers = [('WWW-Authenticate', 'Bearer')]
    elif code == 500:
        error = "Internal error"

    return jsonify(error=error), code, headers


for code in range(400, 599):
    main.app_errorhandler(code)(generic_error_handler)

Fix app error handler raising an attribute error
Fix app error handler raising an attribute error

We're using a single error handler to return a JSON response for
any error code.

The handler expects a flask HTTP error exception with `.code` and
`.description` attributes (like the ones raised by `abort`).

However, if the app raises an exception that's not handled by the
application code the error handler is called with the original
exception object instead. Depending on the exception, that object
might not contain code or description attributes.

In this case, an AttributeError in the error handler itself would
kill the WSGI worker and the application would fail to respond to
the request (leading to a 502 from the nginx proxy).

Replacing attribute access with `getattr` allows us to set the default
values to a 500 response with 'Internal error' for all non-HTTP
exceptions. We still get the error details in the logs, but we don't
want to display any additional information in the HTTP response.

Note: error handlers for HTTP 500 code are not triggered by Flask in
DEBUG mode, so this code usually doesn't run locally.
