# Path: via/exceptions.py
# class BadURL(RequestBasedException):
#     """An invalid URL was discovered."""
# 
#     def __init__(self, message, requests_err=None, url=None):
#         super().__init__(message, requests_err)
#         self.url = url
# 
#     status_int = 400
# 
# class UnhandledUpstreamException(UpstreamServiceError):
#     """Something we did not plan for went wrong."""
# 
#     status_int = 417
# 
# class UpstreamServiceError(RequestBasedException):
#     """Something went wrong when calling an upstream service."""
# 
#     status_int = 409
# 
# class UpstreamTimeout(UpstreamServiceError):
#     """We timed out waiting for an upstream service."""
# 
#     # "504 - Gateway Timeout" is the correct thing to raise, but this
#     # will cause Cloudflare to intercept it:
#     # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error
#     # We're using "408 - Request Timeout" which is technically
#     # incorrect as it implies the user took too long, but has good semantics
#     status_int = 408
# 
# Path: via/resources.py
# def get_original_url(context):
#     """Get the original URL from a provided context object (if any)."""
# 
#     if isinstance(context, QueryURLResource):
#         getter = context.url_from_query
#     elif isinstance(context, PathURLResource):
#         getter = context.url_from_path
#     else:
#         return None
# 
#     try:
#         return getter()
#     except BadURL as err:
#         return err.url
#     except HTTPBadRequest:
#         return None


import h_pyramid_sentry
from pyramid.httpexceptions import HTTPClientError, HTTPNotFound
from pyramid.view import exception_view_config
from via.exceptions import (
    BadURL,
    UnhandledUpstreamException,
    UpstreamServiceError,
    UpstreamTimeout,
)
from via.resources import get_original_url
def _serialise_requests_info(request, response):
    data = {
        "status_code": response.status_code,
        "content_type": response.headers.get("Content-Type"),
    }
    if request:
        data["url"] = request.url

    try:
        data["json"] = response.json()
    except (AttributeError, ValueError):
        pass

    if data.get("json") is None:
        try:
            data["text"] = response.text[:5000]

        except Exception:  # pylint: disable=broad-except
            # Use super broad exceptions so we can't fail here
            data["text"] = "... cannot retrieve ..."

    return data


@exception_view_config(Exception, renderer="via:templates/exception.html.jinja2")
def other_exceptions(exc, request):
    """Catch all errors (Pyramid or Python) and display an HTML page."""

    # We don't want to log errors from upstream services or things which are
    # the user goofing about making bad queries.

# Path: via/exceptions.py
# class BadURL(RequestBasedException):
#     """An invalid URL was discovered."""
# 
#     def __init__(self, message, requests_err=None, url=None):
#         super().__init__(message, requests_err)
#         self.url = url
# 
#     status_int = 400
# 
# class UnhandledUpstreamException(UpstreamServiceError):
#     """Something we did not plan for went wrong."""
# 
#     status_int = 417
# 
# class UpstreamServiceError(RequestBasedException):
#     """Something went wrong when calling an upstream service."""
# 
#     status_int = 409
# 
# class UpstreamTimeout(UpstreamServiceError):
#     """We timed out waiting for an upstream service."""
# 
#     # "504 - Gateway Timeout" is the correct thing to raise, but this
#     # will cause Cloudflare to intercept it:
#     # https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors#502504error
#     # We're using "408 - Request Timeout" which is technically
#     # incorrect as it implies the user took too long, but has good semantics
#     status_int = 408
# 
# Path: via/resources.py
# def get_original_url(context):
#     """Get the original URL from a provided context object (if any)."""
# 
#     if isinstance(context, QueryURLResource):
#         getter = context.url_from_query
#     elif isinstance(context, PathURLResource):
#         getter = context.url_from_path
#     else:
#         return None
# 
#     try:
#         return getter()
#     except BadURL as err:
#         return err.url
#     except HTTPBadRequest:
#         return None


# Path: via/views/exceptions.py
import h_pyramid_sentry
from pyramid.httpexceptions import HTTPClientError, HTTPNotFound
from pyramid.view import exception_view_config
from via.exceptions import (
    BadURL,
    UnhandledUpstreamException,
    UpstreamServiceError,
    UpstreamTimeout,
)
from via.resources import get_original_url

def _serialise_requests_info(request, response):
    data = {
        "status_code": response.status_code,
        "content_type": response.headers.get("Content-Type"),
    }
    if request:
        data["url"] = request.url

    try:
        data["json"] = response.json()
    except (AttributeError, ValueError):
        pass

    if data.get("json") is None:
        try:
            data["text"] = response.text[:5000]

        except Exception:  # pylint: disable=broad-except
            # Use super broad exceptions so we can't fail here
            data["text"] = "... cannot retrieve ..."

    return data


@exception_view_config(Exception, renderer="via:templates/exception.html.jinja2")
def other_exceptions(exc, request):
    """Catch all errors (Pyramid or Python) and display an HTML page."""

    # We don't want to log errors from upstream services or things which are
    # the user goofing about making bad queries.

    if not isinstance(exc, (UpstreamServiceError, BadURL, HTTPClientError)):