|
| 1 | +"""NIAPI exception types. |
| 2 | +
|
| 3 | +Also, defines functions that translate service and repository exceptions |
| 4 | +into HTTP exceptions. |
| 5 | +""" |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import sys |
| 9 | +from typing import TYPE_CHECKING |
| 10 | + |
| 11 | +from litestar.contrib.repository.exceptions import ConflictError, NotFoundError, RepositoryError |
| 12 | +from litestar.exceptions import ( |
| 13 | + HTTPException, |
| 14 | + InternalServerException, |
| 15 | + NotFoundException, |
| 16 | + PermissionDeniedException, |
| 17 | +) |
| 18 | +from litestar.middleware.exceptions._debug_response import create_debug_response |
| 19 | +from litestar.middleware.exceptions.middleware import create_exception_response |
| 20 | +from litestar.status_codes import HTTP_409_CONFLICT, HTTP_500_INTERNAL_SERVER_ERROR |
| 21 | +from structlog.contextvars import bind_contextvars |
| 22 | + |
| 23 | +if TYPE_CHECKING: |
| 24 | + from typing import Any |
| 25 | + |
| 26 | + from litestar.connection import Request |
| 27 | + from litestar.middleware.exceptions.middleware import ExceptionResponseContent |
| 28 | + from litestar.response import Response |
| 29 | + from litestar.types import Scope |
| 30 | + |
| 31 | +__all__ = ( |
| 32 | + "AuthorizationError", |
| 33 | + "HealthCheckConfigurationError", |
| 34 | + "MissingDependencyError", |
| 35 | + "ApplicationError", |
| 36 | + "after_exception_hook_handler", |
| 37 | +) |
| 38 | + |
| 39 | + |
| 40 | +class ApplicationError(Exception): |
| 41 | + """Base exception type for the lib's custom exception types.""" |
| 42 | + |
| 43 | + |
| 44 | +class ApplicationClientError(ApplicationError): |
| 45 | + """Base exception type for client errors.""" |
| 46 | + |
| 47 | + |
| 48 | +class AuthorizationError(ApplicationClientError): |
| 49 | + """A user tried to do something they shouldn't have.""" |
| 50 | + |
| 51 | + |
| 52 | +class MissingDependencyError(ApplicationError, ValueError): |
| 53 | + """A required dependency is not installed.""" |
| 54 | + |
| 55 | + def __init__(self, module: str, config: str | None = None) -> None: |
| 56 | + """Missing Dependency Error. |
| 57 | +
|
| 58 | + Args: |
| 59 | + module: name of the package that should be installed |
| 60 | + config: name of the extra to install the package. |
| 61 | + """ |
| 62 | + config = config if config else module |
| 63 | + super().__init__( |
| 64 | + f"You enabled {config} configuration but package {module!r} is not installed. " |
| 65 | + f'You may need to run: "poetry install niapi[{config}]"', |
| 66 | + ) |
| 67 | + |
| 68 | + |
| 69 | +class HealthCheckConfigurationError(ApplicationError): |
| 70 | + """An error occurred while registering a health check.""" |
| 71 | + |
| 72 | + |
| 73 | +class _HTTPConflictException(HTTPException): |
| 74 | + """Request conflict with the current state of the target resource.""" |
| 75 | + |
| 76 | + status_code = HTTP_409_CONFLICT |
| 77 | + |
| 78 | + |
| 79 | +async def after_exception_hook_handler(exc: Exception, _scope: Scope) -> None: |
| 80 | + """Binds ``exc_info`` key with exception instance as value to structlog |
| 81 | + context vars. |
| 82 | +
|
| 83 | + This must be a coroutine so that it is not wrapped in a thread where we'll lose context. |
| 84 | +
|
| 85 | + Args: |
| 86 | + exc: the exception that was raised. |
| 87 | + _scope: scope of the request |
| 88 | + """ |
| 89 | + if isinstance(exc, ApplicationError): |
| 90 | + return |
| 91 | + if isinstance(exc, HTTPException) and exc.status_code < HTTP_500_INTERNAL_SERVER_ERROR: |
| 92 | + return |
| 93 | + bind_contextvars(exc_info=sys.exc_info()) |
| 94 | + |
| 95 | + |
| 96 | +def exception_to_http_response( |
| 97 | + request: Request[Any, Any, Any], |
| 98 | + exc: ApplicationError | RepositoryError, |
| 99 | +) -> Response[ExceptionResponseContent]: |
| 100 | + """Transform repository exceptions to HTTP exceptions. |
| 101 | +
|
| 102 | + Args: |
| 103 | + request: The request that experienced the exception. |
| 104 | + exc: Exception raised during handling of the request. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + Exception response appropriate to the type of original exception. |
| 108 | + """ |
| 109 | + http_exc: type[HTTPException] |
| 110 | + if isinstance(exc, NotFoundError): |
| 111 | + http_exc = NotFoundException |
| 112 | + elif isinstance(exc, ConflictError | RepositoryError): |
| 113 | + http_exc = _HTTPConflictException |
| 114 | + elif isinstance(exc, AuthorizationError): |
| 115 | + http_exc = PermissionDeniedException |
| 116 | + else: |
| 117 | + http_exc = InternalServerException |
| 118 | + if request.app.debug: |
| 119 | + return create_debug_response(request, exc) |
| 120 | + return create_exception_response(http_exc(detail=str(exc.__cause__))) |
0 commit comments