|
| 1 | +from collections.abc import Callable |
| 2 | + |
| 3 | +import grpc |
| 4 | +from pydantic import ValidationError |
| 5 | + |
| 6 | +from archipy.helpers.interceptors.grpc.base.server_interceptor import ( |
| 7 | + BaseAsyncGrpcServerInterceptor, |
| 8 | + BaseGrpcServerInterceptor, |
| 9 | + MethodName, |
| 10 | +) |
| 11 | +from archipy.helpers.utils.base_utils import BaseUtils |
| 12 | +from archipy.models.errors import InternalError, InvalidArgumentError |
| 13 | +from archipy.models.errors.base_error import BaseError |
| 14 | + |
| 15 | + |
| 16 | +class GrpcServerExceptionInterceptor(BaseGrpcServerInterceptor): |
| 17 | + """A sync gRPC server interceptor for centralized exception handling. |
| 18 | +
|
| 19 | + This interceptor catches all exceptions thrown by gRPC service methods and |
| 20 | + converts them to appropriate gRPC errors, eliminating the need for repetitive |
| 21 | + try-catch blocks in each service method. |
| 22 | + """ |
| 23 | + |
| 24 | + def intercept( |
| 25 | + self, method: Callable, request: object, context: grpc.ServicerContext, method_name_model: MethodName |
| 26 | + ) -> object: |
| 27 | + """Intercepts a sync gRPC server call and handles exceptions. |
| 28 | +
|
| 29 | + Args: |
| 30 | + method: The sync gRPC method being intercepted. |
| 31 | + request: The request object passed to the method. |
| 32 | + context: The context of the sync gRPC call. |
| 33 | + method_name_model: The parsed method name containing package, service, and method components. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + object: The result of the intercepted gRPC method. |
| 37 | +
|
| 38 | + Note: |
| 39 | + This method will not return anything if an exception is handled, |
| 40 | + as the exception handling will abort the gRPC context. |
| 41 | + """ |
| 42 | + try: |
| 43 | + # Execute the gRPC method |
| 44 | + result = method(request, context) |
| 45 | + |
| 46 | + except ValidationError as validation_error: |
| 47 | + BaseUtils.capture_exception(validation_error) |
| 48 | + self._handle_validation_error(validation_error, context) |
| 49 | + |
| 50 | + except BaseError as base_error: |
| 51 | + BaseUtils.capture_exception(base_error) |
| 52 | + base_error.abort_grpc_sync(context) |
| 53 | + |
| 54 | + except Exception as unexpected_error: |
| 55 | + BaseUtils.capture_exception(unexpected_error) |
| 56 | + self._handle_unexpected_error(unexpected_error, context, method_name_model) |
| 57 | + else: |
| 58 | + return result |
| 59 | + |
| 60 | + @staticmethod |
| 61 | + def _handle_validation_error(validation_error: ValidationError, context: grpc.ServicerContext) -> None: |
| 62 | + """Handle Pydantic validation errors. |
| 63 | +
|
| 64 | + Args: |
| 65 | + validation_error: The validation error to handle. |
| 66 | + context: The gRPC context to abort. |
| 67 | + """ |
| 68 | + # Format validation errors for better debugging |
| 69 | + validation_details = BaseUtils.format_validation_errors(validation_error, include_type=True) |
| 70 | + |
| 71 | + InvalidArgumentError( |
| 72 | + argument_name="request_validation", |
| 73 | + additional_data={"validation_errors": validation_details, "error_count": len(validation_error.errors())}, |
| 74 | + ).abort_grpc_sync(context) |
| 75 | + |
| 76 | + @staticmethod |
| 77 | + def _handle_unexpected_error( |
| 78 | + error: Exception, context: grpc.ServicerContext, method_name_model: MethodName |
| 79 | + ) -> None: |
| 80 | + """Handle unexpected errors by converting them to internal errors. |
| 81 | +
|
| 82 | + Args: |
| 83 | + error: The unexpected error to handle. |
| 84 | + context: The gRPC context to abort. |
| 85 | + method_name_model: The method name information for better error tracking. |
| 86 | + """ |
| 87 | + # Capture the exception for monitoring |
| 88 | + InternalError( |
| 89 | + additional_data={ |
| 90 | + "original_error": str(error), |
| 91 | + "error_type": type(error).__name__, |
| 92 | + "service": method_name_model.service, |
| 93 | + "method": method_name_model.method, |
| 94 | + "package": method_name_model.package, |
| 95 | + } |
| 96 | + ).abort_grpc_sync(context) |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def _format_validation_errors(validation_error: ValidationError) -> list[dict[str, str]]: |
| 100 | + """Format Pydantic validation errors into a structured format. |
| 101 | +
|
| 102 | + Args: |
| 103 | + validation_error: The validation error to format. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + A list of formatted validation error details. |
| 107 | +
|
| 108 | + Note: |
| 109 | + This method is deprecated. Use BaseUtils.format_validation_errors instead. |
| 110 | + """ |
| 111 | + return BaseUtils.format_validation_errors(validation_error, include_type=True) |
| 112 | + |
| 113 | + |
| 114 | +class AsyncGrpcServerExceptionInterceptor(BaseAsyncGrpcServerInterceptor): |
| 115 | + """An async gRPC server interceptor for centralized exception handling. |
| 116 | +
|
| 117 | + This interceptor catches all exceptions thrown by gRPC service methods and |
| 118 | + converts them to appropriate gRPC errors, eliminating the need for repetitive |
| 119 | + try-catch blocks in each service method. |
| 120 | + """ |
| 121 | + |
| 122 | + async def intercept( |
| 123 | + self, method: Callable, request: object, context: grpc.aio.ServicerContext, method_name_model: MethodName |
| 124 | + ) -> object: |
| 125 | + """Intercepts an async gRPC server call and handles exceptions. |
| 126 | +
|
| 127 | + Args: |
| 128 | + method: The async gRPC method being intercepted. |
| 129 | + request: The request object passed to the method. |
| 130 | + context: The context of the async gRPC call. |
| 131 | + method_name_model: The parsed method name containing package, service, and method components. |
| 132 | +
|
| 133 | + Returns: |
| 134 | + object: The result of the intercepted gRPC method. |
| 135 | +
|
| 136 | + Note: |
| 137 | + This method will not return anything if an exception is handled, |
| 138 | + as the exception handling will abort the gRPC context. |
| 139 | + """ |
| 140 | + try: |
| 141 | + # Execute the gRPC method |
| 142 | + result = await method(request, context) |
| 143 | + |
| 144 | + except ValidationError as validation_error: |
| 145 | + BaseUtils.capture_exception(validation_error) |
| 146 | + await self._handle_validation_error(validation_error, context) |
| 147 | + |
| 148 | + except BaseError as base_error: |
| 149 | + BaseUtils.capture_exception(base_error) |
| 150 | + await base_error.abort_grpc_async(context) |
| 151 | + |
| 152 | + except Exception as unexpected_error: |
| 153 | + BaseUtils.capture_exception(unexpected_error) |
| 154 | + await self._handle_unexpected_error(unexpected_error, context, method_name_model) |
| 155 | + else: |
| 156 | + return result |
| 157 | + |
| 158 | + @staticmethod |
| 159 | + async def _handle_validation_error(validation_error: ValidationError, context: grpc.aio.ServicerContext) -> None: |
| 160 | + """Handle Pydantic validation errors. |
| 161 | +
|
| 162 | + Args: |
| 163 | + validation_error: The validation error to handle. |
| 164 | + context: The gRPC context to abort. |
| 165 | + """ |
| 166 | + # Format validation errors for better debugging |
| 167 | + validation_details = BaseUtils.format_validation_errors(validation_error, include_type=True) |
| 168 | + |
| 169 | + await InvalidArgumentError( |
| 170 | + argument_name="request_validation", |
| 171 | + additional_data={"validation_errors": validation_details, "error_count": len(validation_error.errors())}, |
| 172 | + ).abort_grpc_async(context) |
| 173 | + |
| 174 | + @staticmethod |
| 175 | + async def _handle_unexpected_error( |
| 176 | + error: Exception, context: grpc.aio.ServicerContext, method_name_model: MethodName |
| 177 | + ) -> None: |
| 178 | + """Handle unexpected errors by converting them to internal errors. |
| 179 | +
|
| 180 | + Args: |
| 181 | + error: The unexpected error to handle. |
| 182 | + context: The gRPC context to abort. |
| 183 | + method_name_model: The method name information for better error tracking. |
| 184 | + """ |
| 185 | + # Capture the exception for monitoring |
| 186 | + await InternalError( |
| 187 | + additional_data={ |
| 188 | + "original_error": str(error), |
| 189 | + "error_type": type(error).__name__, |
| 190 | + "service": method_name_model.service, |
| 191 | + "method": method_name_model.method, |
| 192 | + "package": method_name_model.package, |
| 193 | + } |
| 194 | + ).abort_grpc_async(context) |
| 195 | + |
| 196 | + @staticmethod |
| 197 | + def _format_validation_errors(validation_error: ValidationError) -> list[dict[str, str]]: |
| 198 | + """Format Pydantic validation errors into a structured format. |
| 199 | +
|
| 200 | + Args: |
| 201 | + validation_error: The validation error to format. |
| 202 | +
|
| 203 | + Returns: |
| 204 | + A list of formatted validation error details. |
| 205 | +
|
| 206 | + Note: |
| 207 | + This method is deprecated. Use BaseUtils.format_validation_errors instead. |
| 208 | + """ |
| 209 | + return BaseUtils.format_validation_errors(validation_error, include_type=True) |
0 commit comments