We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `litestar/middleware/exceptions/middleware.py`
Content:
```
1 from __future__ import annotations
2 
3 import pdb  # noqa: T100
4 from dataclasses import asdict, dataclass, field
5 from inspect import getmro
6 from sys import exc_info
7 from traceback import format_exception
8 from typing import TYPE_CHECKING, Any, Type, cast
9 
10 from litestar.connection import Request
11 from litestar.datastructures import Headers
12 from litestar.enums import MediaType, ScopeType
13 from litestar.exceptions import WebSocketException
14 from litestar.middleware.cors import CORSMiddleware
15 from litestar.middleware.exceptions._debug_response import create_debug_response
16 from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
17 
18 __all__ = ("ExceptionHandlerMiddleware", "ExceptionResponseContent", "create_exception_response")
19 
20 
21 if TYPE_CHECKING:
22     from litestar import Response
23     from litestar.app import Litestar
24     from litestar.logging import BaseLoggingConfig
25     from litestar.types import (
26         ASGIApp,
27         ExceptionHandler,
28         ExceptionHandlersMap,
29         Logger,
30         Receive,
31         Scope,
32         Send,
33     )
34     from litestar.types.asgi_types import WebSocketCloseEvent
35 
36 
37 def get_exception_handler(exception_handlers: ExceptionHandlersMap, exc: Exception) -> ExceptionHandler | None:
38     """Given a dictionary that maps exceptions and status codes to handler functions, and an exception, returns the
39     appropriate handler if existing.
40 
41     Status codes are given preference over exception type.
42 
43     If no status code match exists, each class in the MRO of the exception type is checked and
44     the first matching handler is returned.
45 
46     Finally, if a ``500`` handler is registered, it will be returned for any exception that isn't a
47     subclass of :class:`HTTPException <litestar.exceptions.HTTPException>`.
48 
49     Args:
50         exception_handlers: Mapping of status codes and exception types to handlers.
51         exc: Exception Instance to be resolved to a handler.
52 
53     Returns:
54         Optional exception handler callable.
55     """
56     if not exception_handlers:
57         return None
58     status_code: int | None = getattr(exc, "status_code", None)
59     if status_code and (exception_handler := exception_handlers.get(status_code)):
60         return exception_handler
61     for cls in getmro(type(exc)):
62         if cls in exception_handlers:
63             return exception_handlers[cast("Type[Exception]", cls)]
64     if not hasattr(exc, "status_code") and HTTP_500_INTERNAL_SERVER_ERROR in exception_handlers:
65         return exception_handlers[HTTP_500_INTERNAL_SERVER_ERROR]
66     return None
67 
68 
69 @dataclass
70 class ExceptionResponseContent:
71     """Represent the contents of an exception-response."""
72 
73     status_code: int
74     """Exception status code."""
75     detail: str
76     """Exception details or message."""
77     headers: dict[str, str] | None = field(default=None)
78     """Headers to attach to the response."""
79     extra: dict[str, Any] | list[Any] | None = field(default=None)
80     """An extra mapping to attach to the exception."""
81 
82     def to_response(self) -> Response:
83         """Create a response from the model attributes.
84 
85         Returns:
86             A response instance.
87         """
88         from litestar.response import Response
89 
90         return Response(
91             content={k: v for k, v in asdict(self).items() if k != "headers" and v is not None},
92             headers=self.headers,
93             status_code=self.status_code,
94             media_type=MediaType.JSON,
95         )
96 
97 
98 def create_exception_response(exc: Exception) -> Response:
99     """Construct a response from an exception.
100 
101     Notes:
102         - For instances of :class:`HTTPException <litestar.exceptions.HTTPException>` or other exception classes that have a
103           ``status_code`` attribute (e.g. Starlette exceptions), the status code is drawn from the exception, otherwise
104           response status is ``HTTP_500_INTERNAL_SERVER_ERROR``.
105 
106     Args:
107         exc: An exception.
108 
109     Returns:
110         Response: HTTP response constructed from exception details.
111     """
112     content = ExceptionResponseContent(
113         status_code=getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR),
114         detail=getattr(exc, "detail", repr(exc)),
115         headers=getattr(exc, "headers", None),
116         extra=getattr(exc, "extra", None),
117     )
118     return content.to_response()
119 
120 
121 class ExceptionHandlerMiddleware:
122     """Middleware used to wrap an ASGIApp inside a try catch block and handle any exceptions raised.
123 
124     This used in multiple layers of Litestar.
125     """
126 
127     def __init__(self, app: ASGIApp, debug: bool, exception_handlers: ExceptionHandlersMap) -> None:
128         """Initialize ``ExceptionHandlerMiddleware``.
129 
130         Args:
131             app: The ``next`` ASGI app to call.
132             debug: Whether ``debug`` mode is enabled
133             exception_handlers: A dictionary mapping status codes and/or exception types to handler functions.
134         """
135         self.app = app
136         self.exception_handlers = exception_handlers
137         self.debug = debug
138 
139     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
140         """ASGI-callable.
141 
142         Args:
143             scope: The ASGI connection scope.
144             receive: The ASGI receive function.
145             send: The ASGI send function.
146 
147         Returns:
148             None
149         """
150         try:
151             await self.app(scope, receive, send)
152         except Exception as e:  # noqa: BLE001
153             litestar_app = scope["app"]
154 
155             if litestar_app.logging_config and (logger := litestar_app.logger):
156                 self.handle_exception_logging(logger=logger, logging_config=litestar_app.logging_config, scope=scope)
157 
158             for hook in litestar_app.after_exception:
159                 await hook(e, scope)
160 
161             if litestar_app.pdb_on_exception:
162                 pdb.post_mortem()
163 
164             if scope["type"] == ScopeType.HTTP:
165                 await self.handle_request_exception(
166                     litestar_app=litestar_app, scope=scope, receive=receive, send=send, exc=e
167                 )
168             else:
169                 await self.handle_websocket_exception(send=send, exc=e)
170 
171     async def handle_request_exception(
172         self, litestar_app: Litestar, scope: Scope, receive: Receive, send: Send, exc: Exception
173     ) -> None:
174         """Handle exception raised inside 'http' scope routes.
175 
176         Args:
177             litestar_app: The litestar app instance.
178             scope: The ASGI connection scope.
179             receive: The ASGI receive function.
180             send: The ASGI send function.
181             exc: The caught exception.
182 
183         Returns:
184             None.
185         """
186 
187         headers = Headers.from_scope(scope=scope)
188         if litestar_app.cors_config and (origin := headers.get("origin")):
189             cors_middleware = CORSMiddleware(app=self.app, config=litestar_app.cors_config)
190             send = cors_middleware.send_wrapper(send=send, origin=origin, has_cookie="cookie" in headers)
191 
192         exception_handler = get_exception_handler(self.exception_handlers, exc) or self.default_http_exception_handler
193         request = Request[Any, Any, Any](scope=scope, receive=receive, send=send)
194         response = exception_handler(request, exc)
195         await response.to_asgi_response(app=litestar_app, request=request)(scope=scope, receive=receive, send=send)
196 
197     @staticmethod
198     async def handle_websocket_exception(send: Send, exc: Exception) -> None:
199         """Handle exception raised inside 'websocket' scope routes.
200 
201         Args:
202             send: The ASGI send function.
203             exc: The caught exception.
204 
205         Returns:
206             None.
207         """
208         if isinstance(exc, WebSocketException):
209             code = exc.code
210             reason = exc.detail
211         else:
212             code = 4000 + getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR)
213             reason = getattr(exc, "detail", repr(exc))
214         event: WebSocketCloseEvent = {"type": "websocket.close", "code": code, "reason": reason}
215         await send(event)
216 
217     def default_http_exception_handler(self, request: Request, exc: Exception) -> Response[Any]:
218         """Handle an HTTP exception by returning the appropriate response.
219 
220         Args:
221             request: An HTTP Request instance.
222             exc: The caught exception.
223 
224         Returns:
225             An HTTP response.
226         """
227         status_code = getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR)
228         if status_code == HTTP_500_INTERNAL_SERVER_ERROR and self.debug:
229             return create_debug_response(request=request, exc=exc)
230         return create_exception_response(exc)
231 
232     def handle_exception_logging(self, logger: Logger, logging_config: BaseLoggingConfig, scope: Scope) -> None:
233         """Handle logging - if the litestar app has a logging config in place.
234 
235         Args:
236             logger: A logger instance.
237             logging_config: Logging Config instance.
238             scope: The ASGI connection scope.
239 
240         Returns:
241             None
242         """
243         if (
244             logging_config.log_exceptions == "always" or (logging_config.log_exceptions == "debug" and self.debug)
245         ) and logging_config.exception_logging_handler:
246             logging_config.exception_logging_handler(logger, scope, format_exception(*exc_info()))
247
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/litestar/middleware/exceptions/middleware.py b/litestar/middleware/exceptions/middleware.py
--- a/litestar/middleware/exceptions/middleware.py
+++ b/litestar/middleware/exceptions/middleware.py
@@ -109,9 +109,15 @@
     Returns:
         Response: HTTP response constructed from exception details.
     """
+    status_code = getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR)
+    if status_code == HTTP_500_INTERNAL_SERVER_ERROR:
+        detail = "Internal Server Error"
+    else:
+        detail = getattr(exc, "detail", repr(exc))
+
     content = ExceptionResponseContent(
-        status_code=getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR),
-        detail=getattr(exc, "detail", repr(exc)),
+        status_code=status_code,
+        detail=detail,
         headers=getattr(exc, "headers", None),
         extra=getattr(exc, "extra", None),
     )

{"golden_diff": "diff --git a/litestar/middleware/exceptions/middleware.py b/litestar/middleware/exceptions/middleware.py\n--- a/litestar/middleware/exceptions/middleware.py\n+++ b/litestar/middleware/exceptions/middleware.py\n@@ -109,9 +109,15 @@\n     Returns:\n         Response: HTTP response constructed from exception details.\n     \"\"\"\n+    status_code = getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR)\n+    if status_code == HTTP_500_INTERNAL_SERVER_ERROR:\n+        detail = \"Internal Server Error\"\n+    else:\n+        detail = getattr(exc, \"detail\", repr(exc))\n+\n     content = ExceptionResponseContent(\n-        status_code=getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR),\n-        detail=getattr(exc, \"detail\", repr(exc)),\n+        status_code=status_code,\n+        detail=detail,\n         headers=getattr(exc, \"headers\", None),\n         extra=getattr(exc, \"extra\", None),\n     )\n", "issue": "StaticFilesConfig and virtual directories\nI'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. \r\n\r\nThis is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.\r\n\r\nhttps://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32\n", "before_files": [{"content": "from __future__ import annotations\n\nimport pdb  # noqa: T100\nfrom dataclasses import asdict, dataclass, field\nfrom inspect import getmro\nfrom sys import exc_info\nfrom traceback import format_exception\nfrom typing import TYPE_CHECKING, Any, Type, cast\n\nfrom litestar.connection import Request\nfrom litestar.datastructures import Headers\nfrom litestar.enums import MediaType, ScopeType\nfrom litestar.exceptions import WebSocketException\nfrom litestar.middleware.cors import CORSMiddleware\nfrom litestar.middleware.exceptions._debug_response import create_debug_response\nfrom litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR\n\n__all__ = (\"ExceptionHandlerMiddleware\", \"ExceptionResponseContent\", \"create_exception_response\")\n\n\nif TYPE_CHECKING:\n    from litestar import Response\n    from litestar.app import Litestar\n    from litestar.logging import BaseLoggingConfig\n    from litestar.types import (\n        ASGIApp,\n        ExceptionHandler,\n        ExceptionHandlersMap,\n        Logger,\n        Receive,\n        Scope,\n        Send,\n    )\n    from litestar.types.asgi_types import WebSocketCloseEvent\n\n\ndef get_exception_handler(exception_handlers: ExceptionHandlersMap, exc: Exception) -> ExceptionHandler | None:\n    \"\"\"Given a dictionary that maps exceptions and status codes to handler functions, and an exception, returns the\n    appropriate handler if existing.\n\n    Status codes are given preference over exception type.\n\n    If no status code match exists, each class in the MRO of the exception type is checked and\n    the first matching handler is returned.\n\n    Finally, if a ``500`` handler is registered, it will be returned for any exception that isn't a\n    subclass of :class:`HTTPException <litestar.exceptions.HTTPException>`.\n\n    Args:\n        exception_handlers: Mapping of status codes and exception types to handlers.\n        exc: Exception Instance to be resolved to a handler.\n\n    Returns:\n        Optional exception handler callable.\n    \"\"\"\n    if not exception_handlers:\n        return None\n    status_code: int | None = getattr(exc, \"status_code\", None)\n    if status_code and (exception_handler := exception_handlers.get(status_code)):\n        return exception_handler\n    for cls in getmro(type(exc)):\n        if cls in exception_handlers:\n            return exception_handlers[cast(\"Type[Exception]\", cls)]\n    if not hasattr(exc, \"status_code\") and HTTP_500_INTERNAL_SERVER_ERROR in exception_handlers:\n        return exception_handlers[HTTP_500_INTERNAL_SERVER_ERROR]\n    return None\n\n\n@dataclass\nclass ExceptionResponseContent:\n    \"\"\"Represent the contents of an exception-response.\"\"\"\n\n    status_code: int\n    \"\"\"Exception status code.\"\"\"\n    detail: str\n    \"\"\"Exception details or message.\"\"\"\n    headers: dict[str, str] | None = field(default=None)\n    \"\"\"Headers to attach to the response.\"\"\"\n    extra: dict[str, Any] | list[Any] | None = field(default=None)\n    \"\"\"An extra mapping to attach to the exception.\"\"\"\n\n    def to_response(self) -> Response:\n        \"\"\"Create a response from the model attributes.\n\n        Returns:\n            A response instance.\n        \"\"\"\n        from litestar.response import Response\n\n        return Response(\n            content={k: v for k, v in asdict(self).items() if k != \"headers\" and v is not None},\n            headers=self.headers,\n            status_code=self.status_code,\n            media_type=MediaType.JSON,\n        )\n\n\ndef create_exception_response(exc: Exception) -> Response:\n    \"\"\"Construct a response from an exception.\n\n    Notes:\n        - For instances of :class:`HTTPException <litestar.exceptions.HTTPException>` or other exception classes that have a\n          ``status_code`` attribute (e.g. Starlette exceptions), the status code is drawn from the exception, otherwise\n          response status is ``HTTP_500_INTERNAL_SERVER_ERROR``.\n\n    Args:\n        exc: An exception.\n\n    Returns:\n        Response: HTTP response constructed from exception details.\n    \"\"\"\n    content = ExceptionResponseContent(\n        status_code=getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR),\n        detail=getattr(exc, \"detail\", repr(exc)),\n        headers=getattr(exc, \"headers\", None),\n        extra=getattr(exc, \"extra\", None),\n    )\n    return content.to_response()\n\n\nclass ExceptionHandlerMiddleware:\n    \"\"\"Middleware used to wrap an ASGIApp inside a try catch block and handle any exceptions raised.\n\n    This used in multiple layers of Litestar.\n    \"\"\"\n\n    def __init__(self, app: ASGIApp, debug: bool, exception_handlers: ExceptionHandlersMap) -> None:\n        \"\"\"Initialize ``ExceptionHandlerMiddleware``.\n\n        Args:\n            app: The ``next`` ASGI app to call.\n            debug: Whether ``debug`` mode is enabled\n            exception_handlers: A dictionary mapping status codes and/or exception types to handler functions.\n        \"\"\"\n        self.app = app\n        self.exception_handlers = exception_handlers\n        self.debug = debug\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        \"\"\"ASGI-callable.\n\n        Args:\n            scope: The ASGI connection scope.\n            receive: The ASGI receive function.\n            send: The ASGI send function.\n\n        Returns:\n            None\n        \"\"\"\n        try:\n            await self.app(scope, receive, send)\n        except Exception as e:  # noqa: BLE001\n            litestar_app = scope[\"app\"]\n\n            if litestar_app.logging_config and (logger := litestar_app.logger):\n                self.handle_exception_logging(logger=logger, logging_config=litestar_app.logging_config, scope=scope)\n\n            for hook in litestar_app.after_exception:\n                await hook(e, scope)\n\n            if litestar_app.pdb_on_exception:\n                pdb.post_mortem()\n\n            if scope[\"type\"] == ScopeType.HTTP:\n                await self.handle_request_exception(\n                    litestar_app=litestar_app, scope=scope, receive=receive, send=send, exc=e\n                )\n            else:\n                await self.handle_websocket_exception(send=send, exc=e)\n\n    async def handle_request_exception(\n        self, litestar_app: Litestar, scope: Scope, receive: Receive, send: Send, exc: Exception\n    ) -> None:\n        \"\"\"Handle exception raised inside 'http' scope routes.\n\n        Args:\n            litestar_app: The litestar app instance.\n            scope: The ASGI connection scope.\n            receive: The ASGI receive function.\n            send: The ASGI send function.\n            exc: The caught exception.\n\n        Returns:\n            None.\n        \"\"\"\n\n        headers = Headers.from_scope(scope=scope)\n        if litestar_app.cors_config and (origin := headers.get(\"origin\")):\n            cors_middleware = CORSMiddleware(app=self.app, config=litestar_app.cors_config)\n            send = cors_middleware.send_wrapper(send=send, origin=origin, has_cookie=\"cookie\" in headers)\n\n        exception_handler = get_exception_handler(self.exception_handlers, exc) or self.default_http_exception_handler\n        request = Request[Any, Any, Any](scope=scope, receive=receive, send=send)\n        response = exception_handler(request, exc)\n        await response.to_asgi_response(app=litestar_app, request=request)(scope=scope, receive=receive, send=send)\n\n    @staticmethod\n    async def handle_websocket_exception(send: Send, exc: Exception) -> None:\n        \"\"\"Handle exception raised inside 'websocket' scope routes.\n\n        Args:\n            send: The ASGI send function.\n            exc: The caught exception.\n\n        Returns:\n            None.\n        \"\"\"\n        if isinstance(exc, WebSocketException):\n            code = exc.code\n            reason = exc.detail\n        else:\n            code = 4000 + getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR)\n            reason = getattr(exc, \"detail\", repr(exc))\n        event: WebSocketCloseEvent = {\"type\": \"websocket.close\", \"code\": code, \"reason\": reason}\n        await send(event)\n\n    def default_http_exception_handler(self, request: Request, exc: Exception) -> Response[Any]:\n        \"\"\"Handle an HTTP exception by returning the appropriate response.\n\n        Args:\n            request: An HTTP Request instance.\n            exc: The caught exception.\n\n        Returns:\n            An HTTP response.\n        \"\"\"\n        status_code = getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR)\n        if status_code == HTTP_500_INTERNAL_SERVER_ERROR and self.debug:\n            return create_debug_response(request=request, exc=exc)\n        return create_exception_response(exc)\n\n    def handle_exception_logging(self, logger: Logger, logging_config: BaseLoggingConfig, scope: Scope) -> None:\n        \"\"\"Handle logging - if the litestar app has a logging config in place.\n\n        Args:\n            logger: A logger instance.\n            logging_config: Logging Config instance.\n            scope: The ASGI connection scope.\n\n        Returns:\n            None\n        \"\"\"\n        if (\n            logging_config.log_exceptions == \"always\" or (logging_config.log_exceptions == \"debug\" and self.debug)\n        ) and logging_config.exception_logging_handler:\n            logging_config.exception_logging_handler(logger, scope, format_exception(*exc_info()))\n", "path": "litestar/middleware/exceptions/middleware.py"}], "after_files": [{"content": "from __future__ import annotations\n\nimport pdb  # noqa: T100\nfrom dataclasses import asdict, dataclass, field\nfrom inspect import getmro\nfrom sys import exc_info\nfrom traceback import format_exception\nfrom typing import TYPE_CHECKING, Any, Type, cast\n\nfrom litestar.connection import Request\nfrom litestar.datastructures import Headers\nfrom litestar.enums import MediaType, ScopeType\nfrom litestar.exceptions import WebSocketException\nfrom litestar.middleware.cors import CORSMiddleware\nfrom litestar.middleware.exceptions._debug_response import create_debug_response\nfrom litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR\n\n__all__ = (\"ExceptionHandlerMiddleware\", \"ExceptionResponseContent\", \"create_exception_response\")\n\n\nif TYPE_CHECKING:\n    from litestar import Response\n    from litestar.app import Litestar\n    from litestar.logging import BaseLoggingConfig\n    from litestar.types import (\n        ASGIApp,\n        ExceptionHandler,\n        ExceptionHandlersMap,\n        Logger,\n        Receive,\n        Scope,\n        Send,\n    )\n    from litestar.types.asgi_types import WebSocketCloseEvent\n\n\ndef get_exception_handler(exception_handlers: ExceptionHandlersMap, exc: Exception) -> ExceptionHandler | None:\n    \"\"\"Given a dictionary that maps exceptions and status codes to handler functions, and an exception, returns the\n    appropriate handler if existing.\n\n    Status codes are given preference over exception type.\n\n    If no status code match exists, each class in the MRO of the exception type is checked and\n    the first matching handler is returned.\n\n    Finally, if a ``500`` handler is registered, it will be returned for any exception that isn't a\n    subclass of :class:`HTTPException <litestar.exceptions.HTTPException>`.\n\n    Args:\n        exception_handlers: Mapping of status codes and exception types to handlers.\n        exc: Exception Instance to be resolved to a handler.\n\n    Returns:\n        Optional exception handler callable.\n    \"\"\"\n    if not exception_handlers:\n        return None\n    status_code: int | None = getattr(exc, \"status_code\", None)\n    if status_code and (exception_handler := exception_handlers.get(status_code)):\n        return exception_handler\n    for cls in getmro(type(exc)):\n        if cls in exception_handlers:\n            return exception_handlers[cast(\"Type[Exception]\", cls)]\n    if not hasattr(exc, \"status_code\") and HTTP_500_INTERNAL_SERVER_ERROR in exception_handlers:\n        return exception_handlers[HTTP_500_INTERNAL_SERVER_ERROR]\n    return None\n\n\n@dataclass\nclass ExceptionResponseContent:\n    \"\"\"Represent the contents of an exception-response.\"\"\"\n\n    status_code: int\n    \"\"\"Exception status code.\"\"\"\n    detail: str\n    \"\"\"Exception details or message.\"\"\"\n    headers: dict[str, str] | None = field(default=None)\n    \"\"\"Headers to attach to the response.\"\"\"\n    extra: dict[str, Any] | list[Any] | None = field(default=None)\n    \"\"\"An extra mapping to attach to the exception.\"\"\"\n\n    def to_response(self) -> Response:\n        \"\"\"Create a response from the model attributes.\n\n        Returns:\n            A response instance.\n        \"\"\"\n        from litestar.response import Response\n\n        return Response(\n            content={k: v for k, v in asdict(self).items() if k != \"headers\" and v is not None},\n            headers=self.headers,\n            status_code=self.status_code,\n            media_type=MediaType.JSON,\n        )\n\n\ndef create_exception_response(exc: Exception) -> Response:\n    \"\"\"Construct a response from an exception.\n\n    Notes:\n        - For instances of :class:`HTTPException <litestar.exceptions.HTTPException>` or other exception classes that have a\n          ``status_code`` attribute (e.g. Starlette exceptions), the status code is drawn from the exception, otherwise\n          response status is ``HTTP_500_INTERNAL_SERVER_ERROR``.\n\n    Args:\n        exc: An exception.\n\n    Returns:\n        Response: HTTP response constructed from exception details.\n    \"\"\"\n    status_code = getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR)\n    if status_code == HTTP_500_INTERNAL_SERVER_ERROR:\n        detail = \"Internal Server Error\"\n    else:\n        detail = getattr(exc, \"detail\", repr(exc))\n\n    content = ExceptionResponseContent(\n        status_code=status_code,\n        detail=detail,\n        headers=getattr(exc, \"headers\", None),\n        extra=getattr(exc, \"extra\", None),\n    )\n    return content.to_response()\n\n\nclass ExceptionHandlerMiddleware:\n    \"\"\"Middleware used to wrap an ASGIApp inside a try catch block and handle any exceptions raised.\n\n    This used in multiple layers of Litestar.\n    \"\"\"\n\n    def __init__(self, app: ASGIApp, debug: bool, exception_handlers: ExceptionHandlersMap) -> None:\n        \"\"\"Initialize ``ExceptionHandlerMiddleware``.\n\n        Args:\n            app: The ``next`` ASGI app to call.\n            debug: Whether ``debug`` mode is enabled\n            exception_handlers: A dictionary mapping status codes and/or exception types to handler functions.\n        \"\"\"\n        self.app = app\n        self.exception_handlers = exception_handlers\n        self.debug = debug\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        \"\"\"ASGI-callable.\n\n        Args:\n            scope: The ASGI connection scope.\n            receive: The ASGI receive function.\n            send: The ASGI send function.\n\n        Returns:\n            None\n        \"\"\"\n        try:\n            await self.app(scope, receive, send)\n        except Exception as e:  # noqa: BLE001\n            litestar_app = scope[\"app\"]\n\n            if litestar_app.logging_config and (logger := litestar_app.logger):\n                self.handle_exception_logging(logger=logger, logging_config=litestar_app.logging_config, scope=scope)\n\n            for hook in litestar_app.after_exception:\n                await hook(e, scope)\n\n            if litestar_app.pdb_on_exception:\n                pdb.post_mortem()\n\n            if scope[\"type\"] == ScopeType.HTTP:\n                await self.handle_request_exception(\n                    litestar_app=litestar_app, scope=scope, receive=receive, send=send, exc=e\n                )\n            else:\n                await self.handle_websocket_exception(send=send, exc=e)\n\n    async def handle_request_exception(\n        self, litestar_app: Litestar, scope: Scope, receive: Receive, send: Send, exc: Exception\n    ) -> None:\n        \"\"\"Handle exception raised inside 'http' scope routes.\n\n        Args:\n            litestar_app: The litestar app instance.\n            scope: The ASGI connection scope.\n            receive: The ASGI receive function.\n            send: The ASGI send function.\n            exc: The caught exception.\n\n        Returns:\n            None.\n        \"\"\"\n\n        headers = Headers.from_scope(scope=scope)\n        if litestar_app.cors_config and (origin := headers.get(\"origin\")):\n            cors_middleware = CORSMiddleware(app=self.app, config=litestar_app.cors_config)\n            send = cors_middleware.send_wrapper(send=send, origin=origin, has_cookie=\"cookie\" in headers)\n\n        exception_handler = get_exception_handler(self.exception_handlers, exc) or self.default_http_exception_handler\n        request = Request[Any, Any, Any](scope=scope, receive=receive, send=send)\n        response = exception_handler(request, exc)\n        await response.to_asgi_response(app=litestar_app, request=request)(scope=scope, receive=receive, send=send)\n\n    @staticmethod\n    async def handle_websocket_exception(send: Send, exc: Exception) -> None:\n        \"\"\"Handle exception raised inside 'websocket' scope routes.\n\n        Args:\n            send: The ASGI send function.\n            exc: The caught exception.\n\n        Returns:\n            None.\n        \"\"\"\n        if isinstance(exc, WebSocketException):\n            code = exc.code\n            reason = exc.detail\n        else:\n            code = 4000 + getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR)\n            reason = getattr(exc, \"detail\", repr(exc))\n        event: WebSocketCloseEvent = {\"type\": \"websocket.close\", \"code\": code, \"reason\": reason}\n        await send(event)\n\n    def default_http_exception_handler(self, request: Request, exc: Exception) -> Response[Any]:\n        \"\"\"Handle an HTTP exception by returning the appropriate response.\n\n        Args:\n            request: An HTTP Request instance.\n            exc: The caught exception.\n\n        Returns:\n            An HTTP response.\n        \"\"\"\n        status_code = getattr(exc, \"status_code\", HTTP_500_INTERNAL_SERVER_ERROR)\n        if status_code == HTTP_500_INTERNAL_SERVER_ERROR and self.debug:\n            return create_debug_response(request=request, exc=exc)\n        return create_exception_response(exc)\n\n    def handle_exception_logging(self, logger: Logger, logging_config: BaseLoggingConfig, scope: Scope) -> None:\n        \"\"\"Handle logging - if the litestar app has a logging config in place.\n\n        Args:\n            logger: A logger instance.\n            logging_config: Logging Config instance.\n            scope: The ASGI connection scope.\n\n        Returns:\n            None\n        \"\"\"\n        if (\n            logging_config.log_exceptions == \"always\" or (logging_config.log_exceptions == \"debug\" and self.debug)\n        ) and logging_config.exception_logging_handler:\n            logging_config.exception_logging_handler(logger, scope, format_exception(*exc_info()))\n", "path": "litestar/middleware/exceptions/middleware.py"}]}