Closure: Json URL error handler
    Checks if request matches provided url prefix and returns json response if
    it does. Otherwise falls back to template error handler. This is usefull
    if you want to return json errors for a subset of your routes.

    Register this by calling a closure:
        register_error_handler(app, json_url_handler([
            '/url/path/one/',
            '/some/other/relative/url/',
        ]))

    :param urls: iterable or string, list of url prefixes
    :return:

def json_url_error_handler(urls=()):
    """
    Closure: Json URL error handler
    Checks if request matches provided url prefix and returns json response if
    it does. Otherwise falls back to template error handler. This is usefull
    if you want to return json errors for a subset of your routes.

    Register this by calling a closure:
        register_error_handler(app, json_url_handler([
            '/url/path/one/',
            '/some/other/relative/url/',
        ]))

    :param urls: iterable or string, list of url prefixes
    :return:
    """
    if type(urls) is str:
        urls = [urls]

    # the handler itself
    def handler(exception):
        http_exception = isinstance(exception, exceptions.HTTPException)
        code = exception.code if http_exception else 500

        # log exceptions only (app debug should be off)
        if code == 500:
            current_app.logger.error(exception)

        # if matches one of urls, return json
        if has_app_context() and has_request_context():
            for prefix in urls:
                prefix = prefix.strip('/')
                prefix = '/' + prefix + '/' if len(prefix) else '/'
                if request.path.startswith(prefix):
                    return json_error_handler(exception)

        # otherwise fall back to error page handler
        return template_error_handler(exception)

    return handler