
    Yji                     ,   d Z ddlZddlmZ ddlmZmZmZmZ ddlm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ  ej,                  e      Zde	dedefdZde	dedefdZdedeee   ef   fdZde	dedefdZde	dedefdZeeeeeeeeiZ y)zw
Error Handlers for FastAPI Application

Updated for Python 3.12 with improved error handling, logging, and structure.
    N)datetime)DictListTupleUnion)Request)HTTPExceptionRequestValidationError)status)JSONResponse)APIException)ErrorDetailErrorResponseModelrequestexcreturnc                   K   t        | j                  dd      }t        j                  d|j                   d|j
                   d|j                   d| d| j                  j                   d| j                          t        |j
                  |j                  |j                  |j                  |xs |j                  	      }t        |j
                  |j                         
      S w)z
    Custom error handler for APIException.
    
    Maintains uniform response structure throughout the application
    with enhanced logging and request tracking.
    
request_idNzAPI Exception:  | Status: z | Module:  | RequestID: 	 | Path:  | Method: status_codemessageerror	timestampr   r   content)getattrstateloggerr   r   r   moduleurlpathmethodr   r   r   r   
model_dump)r   r   r   error_responses       S/var/www/html/hwPaymentPortal-be-dev/hw-payment-portal-api/src/middleware/errors.pyapi_exception_handlerr*      s      d;J LL
#++ '??# $::,  \ "!!" #>>"	$ (OOii--/N OO))+ s   C&C(c                   K   t        | j                  dd      }t        j                         j	                         dz   }t
        j                  d|j                   d|j                   d| d| j                  j                   d| j                   
       d	|j                  t        |d
d      d}t        |j                  |j                  xs d|||      }t        |j                  |j                               S w)z
    Handler for standard FastAPI HTTPExceptions.
    
    Converts HTTPExceptions to our standardized error response format.
    r   NZzHTTP Exception: r   r   r   r   r	   headers)typedetailr-   zHTTP error occurredr   r   )r    r!   r   utcnow	isoformatr"   warningr/   r   r$   r%   r&   r   r   r'   )r   r   r   r   error_detailsr(   s         r)   http_exception_handlerr4   8   s      d;J!++-3I NN
3::, '??# $ \ "!!" #>>"		$  **3	40M (OO

33N OO))+ s   C;C=c           	         g }d}| j                         D ]  }|j                  dd      }|rt        |d         nd}dj                  d |D              }|j	                  dd	      }|j                  d
d      }|j	                  dd| d      j	                  dd| d      j	                  dd| d      }	t        ||	|j                  dd            }
|j                  |
       |	} ||fS )ai  
    Parse Pydantic validation errors into structured error details.
    
    Converts RequestValidationError into a list of ErrorDetail objects
    with improved field name handling and error message formatting.
    
    Args:
        exc: The RequestValidationError from Pydantic
        
    Returns:
        Tuple of (parsed_errors, last_error_message)
    zRequest validation failedloc unknown.c              3   2   K   | ]  }t        |        y w)N)str).0r6   s     r)   	<genexpr>z)parse_validation_error.<locals>.<genexpr>u   s      ?cS ?s   zbody. msgzInvalid valuez
this value'valuevaluesr.   validation_error)fieldr   code)errorsgetr<   joinreplacer   append)r   parsed_errorslast_error_message
error_dict	error_loc
field_namelocation_pathclean_locationraw_messageformatted_messageerror_details              r)   parse_validation_errorrV   _   s    (*M4jjl /
NN5"-	+4S2')
  ?Y ??&..w; !nnUO<W\Qzl!#45WW*Q/0WX:,a01	 	 #%(:;
 	\*.5/8 ,,,    c                   K   t        | j                  dd      }t        j                         j	                         dz   }t        |      \  }}t        j                  d| dt        |       d| d| j                  j                   d| j                   
       t        t        j                  ||D cg c]  }|j                          c}||	      }t!        t        j                  |j                         
      S c c}w w)z
    Handler for Pydantic validation errors.
    
    Converts RequestValidationError into standardized error response
    with detailed field-level error information.
    r   Nr,   zValidation Error: z | Fields: r   r   r   r   r   )r    r!   r   r0   r1   rV   r"   r2   lenr$   r%   r&   r   r   HTTP_422_UNPROCESSABLE_ENTITYr'   r   )r   r   r   r   rL   summary_messager   r(   s           r)   validation_error_handlerr\      s      d;J!++-3I &<C%@"M? NN
_- .}%& ' \ "!!" #>>"		$ (88/<=eu!=N 88))+  >s   B/D 1C;8D c                   K   t        | j                  dd      }t        j                         j	                         dz   }t
        j                  dt        |      j                   dt        |       d| d| j                  j                   d| j                   
d	
       t        t        j                  dddd||      }t!        t        j                  |j#                               S w)z
    Catch-all handler for unhandled exceptions.
    
    Provides a safety net for any unexpected errors while maintaining
    consistent error response structure.
    r   Nr,   zUnhandled Exception: z: r   r   r   T)exc_infozAn unexpected error occurredInternalServerErrorz)Please try again later or contact support)r.   r/   r   r   )r    r!   r   r0   r1   r"   r   r.   __name__r<   r$   r%   r&   r   r   HTTP_500_INTERNAL_SERVER_ERRORr   r'   )r   r   r   r   r(   s        r)   general_exception_handlerrb      s      d;J!++-3I LL
S	 2 232c#hZ @ \ "!!" #>>"	$    (99.)A
 	N 99))+ s   C'C))!__doc__loggingr   typingr   r   r   r   fastapir   fastapi.exceptionsr	   r
   	starletter   starlette.responsesr   src.core.exceptionsr   src.apps.base.schemas.responsesr   r   	getLoggerr`   r"   r*   r4   r<   rV   r\   	Exceptionrb   EXCEPTION_HANDLERSr7   rW   r)   <module>ro      s   
   + +  D  , , K			8	$   |    F$' $ $, $N,- 6 ,-5kARTWAW;X ,-^$$1$$N"W "9 " "N ')4(	 rW   