o
    NK&hz                     @  s   d dl mZ d dlmZ d dlmZmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ d d	lmZ G d
d dZdS )    )annotations)Optional)BaseRendererTextRendererexception_response)ServerError)error_logger)RouteHandler)Request)text)HTTPResponsec                   @  sp   e Zd ZdZefd$ddZd%d&d	d
Zd'ddZd%d(ddZd%d&ddZ	eZ
dd Zd)d d!Zed*d"d#ZdS )+ErrorHandlera  Process and handle all uncaught exceptions.

    This error handling framework is built into the core that can be extended
    by the developers to perform a wide range of tasks from recording the error
    stats to reporting them to an external service that can be used for
    realtime alerting system.

    Args:
        base (BaseRenderer): The renderer to use for the error pages.
    basetype[BaseRenderer]c                 C  s   i | _ d| _|| _d S )NF)cached_handlersdebugr   )selfr    r   G/var/www/html/venv/lib/python3.10/site-packages/sanic/handlers/error.py__init__   s   
zErrorHandler.__init__N
route_nameOptional[str]c                 C  s   |  ||S N)lookup)r   	exceptionr   r   r   r   _full_lookup$   s   zErrorHandler._full_lookupkey)tuple[type[BaseException], Optional[str]]handlerr	   returnNonec                 C  sD   || j v r|\}}|d u rd}d| d| }t||| j |< d S )N__ALL_ROUTES__z1Duplicate exception handler definition on: route=z and exception=)r   r   )r   r   r   excnamemessager   r   r   _add'   s   
zErrorHandler._addroute_namesOptional[list[str]]c                 C  s6   |r|D ]
}|  ||f| qdS |  |df| dS )aj  Add a new exception handler to an already existing handler object.

        Args:
            exception (sanic.exceptions.SanicException or Exception): Type
                of exception that needs to be handled.
            handler (function): Reference to the function that will
                handle the exception.

        Returns:
            None

        N)r%   )r   r   r   r&   router   r   r   add8   s
   zErrorHandler.addc                 C  s   t |}|dfD ]}||f}| j|}|r|  S q|dfD ]+}t |D ]#}||f}|| jv rC| j| }|| j||f< |    S |tu rI nq&qd| j||f< d}|S )a  Lookup the existing instance of `ErrorHandler` and fetch the registered handler for a specific type of exception.

        This method leverages a dict lookup to speedup the retrieval process.

        Args:
            exception (sanic.exceptions.SanicException or Exception): Type
                of exception.

        Returns:
            Registered function if found, ``None`` otherwise.

        N)typer   getmroBaseException)r   r   r   exception_classr#   exception_keyr   ancestorr   r   r   r   K   s,   

zErrorHandler.lookupc                 C  s   |r|j nd}| ||}d}z|r|||}|du r$| ||}W |S W |S  ty`   zt|j}W n ty?   d}Y nw d}t||j	| | j
rYt||j	|f d Y S tdd Y S w )a  Fetch and executes an exception handler and returns a response object.

        Args:
            request (sanic.request.Request): Instance of the request.
            exception (sanic.exceptions.SanicException or Exception): Exception to handle.

        Returns:
            Wrap the return value obtained from the `default` function or the registered handler for that type of exception.

        Nunknownz6Exception raised in exception handler "%s" for uri: %si  z)An error occurred while handling an error)r#   _lookupdefault	ExceptionreprurlAttributeErrorr   r   __name__r   r   )r   requestr   r   r   responser6   response_messager   r   r   r:   r   s0   
zErrorHandler.responser9   r
   r   r4   r   c                 C  s,   |  || |jjj}t||| j| j|dS )a  Provide a default behavior for the objects of ErrorHandler.

        If a developer chooses to extend the ErrorHandler, they can
        provide a custom implementation for this method to behave in a way
        they see fit.

        Args:
            request (sanic.request.Request): Incoming request.
            exception (sanic.exceptions.SanicException or Exception): Exception object.

        Returns:
            HTTPResponse: The response object.

        Examples:
            ```python
            class CustomErrorHandler(ErrorHandler):
                def default(self, request: Request, exception: Exception) -> HTTPResponse:
                    # Custom logic for handling the exception and creating a response
                    custom_response = my_custom_logic(request, exception)
                    return custom_response

            app = Sanic("MyApp", error_handler=CustomErrorHandler())
            ```
        )r   r   fallback)logappconfigFALLBACK_ERROR_FORMATr   r   r   )r   r9   r   r<   r   r   r   r3      s   
zErrorHandler.defaultc                 C  sf   t |dd}t | jjdd}|du s|du r1zt| j}W n ty(   d}Y nw td| dS dS )a(  Logs information about an incoming request and the associated exception.

        Args:
            request (Request): The incoming request to be logged.
            exception (Exception): The exception that occurred during the handling of the request.

        Returns:
            None
        quietFNOISY_EXCEPTIONSTr1   z)Exception occurred while handling uri: %sN)getattrr>   r?   r5   r6   r7   r   r   )r9   r   rA   noisyr6   r   r   r   r=      s   zErrorHandler.log)r   r   r   )r   r   )r   r   r   r	   r   r    )r&   r'   )r9   r
   r   r4   r   r   )r9   r
   r   r4   r   r    )r8   
__module____qualname____doc__r   r   r   r%   r)   r   r2   r:   r3   staticmethodr=   r   r   r   r   r      s    

%
##r   N)
__future__r   typingr   sanic.errorpagesr   r   r   sanic.exceptionsr   	sanic.logr   sanic.models.handler_typesr	   sanic.request.typesr
   sanic.responser   sanic.response.typesr   r   r   r   r   r   <module>   s    