We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Background tasks exception handler
Currently, if a background task faces an exception, it isn't handled and there's no way to handle it (rather than wrapping the task)
My suggestion is to be able to add exception handler for background tasks, as there is for requests.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `starlette/middleware/errors.py`
Content:
```
1 import asyncio
2 import html
3 import inspect
4 import traceback
5 import typing
6 
7 from starlette.concurrency import run_in_threadpool
8 from starlette.requests import Request
9 from starlette.responses import HTMLResponse, PlainTextResponse, Response
10 from starlette.types import ASGIApp, Message, Receive, Scope, Send
11 
12 STYLES = """
13 p {
14     color: #211c1c;
15 }
16 .traceback-container {
17     border: 1px solid #038BB8;
18 }
19 .traceback-title {
20     background-color: #038BB8;
21     color: lemonchiffon;
22     padding: 12px;
23     font-size: 20px;
24     margin-top: 0px;
25 }
26 .frame-line {
27     padding-left: 10px;
28     font-family: monospace;
29 }
30 .frame-filename {
31     font-family: monospace;
32 }
33 .center-line {
34     background-color: #038BB8;
35     color: #f9f6e1;
36     padding: 5px 0px 5px 5px;
37 }
38 .lineno {
39     margin-right: 5px;
40 }
41 .frame-title {
42     font-weight: unset;
43     padding: 10px 10px 10px 10px;
44     background-color: #E4F4FD;
45     margin-right: 10px;
46     color: #191f21;
47     font-size: 17px;
48     border: 1px solid #c7dce8;
49 }
50 .collapse-btn {
51     float: right;
52     padding: 0px 5px 1px 5px;
53     border: solid 1px #96aebb;
54     cursor: pointer;
55 }
56 .collapsed {
57   display: none;
58 }
59 .source-code {
60   font-family: courier;
61   font-size: small;
62   padding-bottom: 10px;
63 }
64 """
65 
66 JS = """
67 <script type="text/javascript">
68     function collapse(element){
69         const frameId = element.getAttribute("data-frame-id");
70         const frame = document.getElementById(frameId);
71 
72         if (frame.classList.contains("collapsed")){
73             element.innerHTML = "&#8210;";
74             frame.classList.remove("collapsed");
75         } else {
76             element.innerHTML = "+";
77             frame.classList.add("collapsed");
78         }
79     }
80 </script>
81 """
82 
83 TEMPLATE = """
84 <html>
85     <head>
86         <style type='text/css'>
87             {styles}
88         </style>
89         <title>Starlette Debugger</title>
90     </head>
91     <body>
92         <h1>500 Server Error</h1>
93         <h2>{error}</h2>
94         <div class="traceback-container">
95             <p class="traceback-title">Traceback</p>
96             <div>{exc_html}</div>
97         </div>
98         {js}
99     </body>
100 </html>
101 """
102 
103 FRAME_TEMPLATE = """
104 <div>
105     <p class="frame-title">File <span class="frame-filename">{frame_filename}</span>,
106     line <i>{frame_lineno}</i>,
107     in <b>{frame_name}</b>
108     <span class="collapse-btn" data-frame-id="{frame_filename}-{frame_lineno}" onclick="collapse(this)">{collapse_button}</span>
109     </p>
110     <div id="{frame_filename}-{frame_lineno}" class="source-code {collapsed}">{code_context}</div>
111 </div>
112 """  # noqa: E501
113 
114 LINE = """
115 <p><span class="frame-line">
116 <span class="lineno">{lineno}.</span> {line}</span></p>
117 """
118 
119 CENTER_LINE = """
120 <p class="center-line"><span class="frame-line center-line">
121 <span class="lineno">{lineno}.</span> {line}</span></p>
122 """
123 
124 
125 class ServerErrorMiddleware:
126     """
127     Handles returning 500 responses when a server error occurs.
128 
129     If 'debug' is set, then traceback responses will be returned,
130     otherwise the designated 'handler' will be called.
131 
132     This middleware class should generally be used to wrap *everything*
133     else up, so that unhandled exceptions anywhere in the stack
134     always result in an appropriate 500 response.
135     """
136 
137     def __init__(
138         self, app: ASGIApp, handler: typing.Callable = None, debug: bool = False
139     ) -> None:
140         self.app = app
141         self.handler = handler
142         self.debug = debug
143 
144     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
145         if scope["type"] != "http":
146             await self.app(scope, receive, send)
147             return
148 
149         response_started = False
150 
151         async def _send(message: Message) -> None:
152             nonlocal response_started, send
153 
154             if message["type"] == "http.response.start":
155                 response_started = True
156             await send(message)
157 
158         try:
159             await self.app(scope, receive, _send)
160         except Exception as exc:
161             if not response_started:
162                 request = Request(scope)
163                 if self.debug:
164                     # In debug mode, return traceback responses.
165                     response = self.debug_response(request, exc)
166                 elif self.handler is None:
167                     # Use our default 500 error handler.
168                     response = self.error_response(request, exc)
169                 else:
170                     # Use an installed 500 error handler.
171                     if asyncio.iscoroutinefunction(self.handler):
172                         response = await self.handler(request, exc)
173                     else:
174                         response = await run_in_threadpool(self.handler, request, exc)
175 
176                 await response(scope, receive, send)
177 
178             # We always continue to raise the exception.
179             # This allows servers to log the error, or allows test clients
180             # to optionally raise the error within the test case.
181             raise exc
182 
183     def format_line(
184         self, index: int, line: str, frame_lineno: int, frame_index: int
185     ) -> str:
186         values = {
187             # HTML escape - line could contain < or >
188             "line": html.escape(line).replace(" ", "&nbsp"),
189             "lineno": (frame_lineno - frame_index) + index,
190         }
191 
192         if index != frame_index:
193             return LINE.format(**values)
194         return CENTER_LINE.format(**values)
195 
196     def generate_frame_html(self, frame: inspect.FrameInfo, is_collapsed: bool) -> str:
197         code_context = "".join(
198             self.format_line(index, line, frame.lineno, frame.index)  # type: ignore
199             for index, line in enumerate(frame.code_context or [])
200         )
201 
202         values = {
203             # HTML escape - filename could contain < or >, especially if it's a virtual
204             # file e.g. <stdin> in the REPL
205             "frame_filename": html.escape(frame.filename),
206             "frame_lineno": frame.lineno,
207             # HTML escape - if you try very hard it's possible to name a function with <
208             # or >
209             "frame_name": html.escape(frame.function),
210             "code_context": code_context,
211             "collapsed": "collapsed" if is_collapsed else "",
212             "collapse_button": "+" if is_collapsed else "&#8210;",
213         }
214         return FRAME_TEMPLATE.format(**values)
215 
216     def generate_html(self, exc: Exception, limit: int = 7) -> str:
217         traceback_obj = traceback.TracebackException.from_exception(
218             exc, capture_locals=True
219         )
220 
221         exc_html = ""
222         is_collapsed = False
223         exc_traceback = exc.__traceback__
224         if exc_traceback is not None:
225             frames = inspect.getinnerframes(exc_traceback, limit)
226             for frame in reversed(frames):
227                 exc_html += self.generate_frame_html(frame, is_collapsed)
228                 is_collapsed = True
229 
230         # escape error class and text
231         error = (
232             f"{html.escape(traceback_obj.exc_type.__name__)}: "
233             f"{html.escape(str(traceback_obj))}"
234         )
235 
236         return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)
237 
238     def generate_plain_text(self, exc: Exception) -> str:
239         return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
240 
241     def debug_response(self, request: Request, exc: Exception) -> Response:
242         accept = request.headers.get("accept", "")
243 
244         if "text/html" in accept:
245             content = self.generate_html(exc)
246             return HTMLResponse(content, status_code=500)
247         content = self.generate_plain_text(exc)
248         return PlainTextResponse(content, status_code=500)
249 
250     def error_response(self, request: Request, exc: Exception) -> Response:
251         return PlainTextResponse("Internal Server Error", status_code=500)
252
```
--- 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/starlette/middleware/errors.py b/starlette/middleware/errors.py
--- a/starlette/middleware/errors.py
+++ b/starlette/middleware/errors.py
@@ -158,21 +158,21 @@
         try:
             await self.app(scope, receive, _send)
         except Exception as exc:
-            if not response_started:
-                request = Request(scope)
-                if self.debug:
-                    # In debug mode, return traceback responses.
-                    response = self.debug_response(request, exc)
-                elif self.handler is None:
-                    # Use our default 500 error handler.
-                    response = self.error_response(request, exc)
+            request = Request(scope)
+            if self.debug:
+                # In debug mode, return traceback responses.
+                response = self.debug_response(request, exc)
+            elif self.handler is None:
+                # Use our default 500 error handler.
+                response = self.error_response(request, exc)
+            else:
+                # Use an installed 500 error handler.
+                if asyncio.iscoroutinefunction(self.handler):
+                    response = await self.handler(request, exc)
                 else:
-                    # Use an installed 500 error handler.
-                    if asyncio.iscoroutinefunction(self.handler):
-                        response = await self.handler(request, exc)
-                    else:
-                        response = await run_in_threadpool(self.handler, request, exc)
+                    response = await run_in_threadpool(self.handler, request, exc)
 
+            if not response_started:
                 await response(scope, receive, send)
 
             # We always continue to raise the exception.

{"golden_diff": "diff --git a/starlette/middleware/errors.py b/starlette/middleware/errors.py\n--- a/starlette/middleware/errors.py\n+++ b/starlette/middleware/errors.py\n@@ -158,21 +158,21 @@\n         try:\n             await self.app(scope, receive, _send)\n         except Exception as exc:\n-            if not response_started:\n-                request = Request(scope)\n-                if self.debug:\n-                    # In debug mode, return traceback responses.\n-                    response = self.debug_response(request, exc)\n-                elif self.handler is None:\n-                    # Use our default 500 error handler.\n-                    response = self.error_response(request, exc)\n+            request = Request(scope)\n+            if self.debug:\n+                # In debug mode, return traceback responses.\n+                response = self.debug_response(request, exc)\n+            elif self.handler is None:\n+                # Use our default 500 error handler.\n+                response = self.error_response(request, exc)\n+            else:\n+                # Use an installed 500 error handler.\n+                if asyncio.iscoroutinefunction(self.handler):\n+                    response = await self.handler(request, exc)\n                 else:\n-                    # Use an installed 500 error handler.\n-                    if asyncio.iscoroutinefunction(self.handler):\n-                        response = await self.handler(request, exc)\n-                    else:\n-                        response = await run_in_threadpool(self.handler, request, exc)\n+                    response = await run_in_threadpool(self.handler, request, exc)\n \n+            if not response_started:\n                 await response(scope, receive, send)\n \n             # We always continue to raise the exception.\n", "issue": "Background tasks exception handler\nCurrently, if a background task faces an exception, it isn't handled and there's no way to handle it (rather than wrapping the task)\r\nMy suggestion is to be able to add exception handler for background tasks, as there is for requests.\n", "before_files": [{"content": "import asyncio\nimport html\nimport inspect\nimport traceback\nimport typing\n\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, PlainTextResponse, Response\nfrom starlette.types import ASGIApp, Message, Receive, Scope, Send\n\nSTYLES = \"\"\"\np {\n    color: #211c1c;\n}\n.traceback-container {\n    border: 1px solid #038BB8;\n}\n.traceback-title {\n    background-color: #038BB8;\n    color: lemonchiffon;\n    padding: 12px;\n    font-size: 20px;\n    margin-top: 0px;\n}\n.frame-line {\n    padding-left: 10px;\n    font-family: monospace;\n}\n.frame-filename {\n    font-family: monospace;\n}\n.center-line {\n    background-color: #038BB8;\n    color: #f9f6e1;\n    padding: 5px 0px 5px 5px;\n}\n.lineno {\n    margin-right: 5px;\n}\n.frame-title {\n    font-weight: unset;\n    padding: 10px 10px 10px 10px;\n    background-color: #E4F4FD;\n    margin-right: 10px;\n    color: #191f21;\n    font-size: 17px;\n    border: 1px solid #c7dce8;\n}\n.collapse-btn {\n    float: right;\n    padding: 0px 5px 1px 5px;\n    border: solid 1px #96aebb;\n    cursor: pointer;\n}\n.collapsed {\n  display: none;\n}\n.source-code {\n  font-family: courier;\n  font-size: small;\n  padding-bottom: 10px;\n}\n\"\"\"\n\nJS = \"\"\"\n<script type=\"text/javascript\">\n    function collapse(element){\n        const frameId = element.getAttribute(\"data-frame-id\");\n        const frame = document.getElementById(frameId);\n\n        if (frame.classList.contains(\"collapsed\")){\n            element.innerHTML = \"&#8210;\";\n            frame.classList.remove(\"collapsed\");\n        } else {\n            element.innerHTML = \"+\";\n            frame.classList.add(\"collapsed\");\n        }\n    }\n</script>\n\"\"\"\n\nTEMPLATE = \"\"\"\n<html>\n    <head>\n        <style type='text/css'>\n            {styles}\n        </style>\n        <title>Starlette Debugger</title>\n    </head>\n    <body>\n        <h1>500 Server Error</h1>\n        <h2>{error}</h2>\n        <div class=\"traceback-container\">\n            <p class=\"traceback-title\">Traceback</p>\n            <div>{exc_html}</div>\n        </div>\n        {js}\n    </body>\n</html>\n\"\"\"\n\nFRAME_TEMPLATE = \"\"\"\n<div>\n    <p class=\"frame-title\">File <span class=\"frame-filename\">{frame_filename}</span>,\n    line <i>{frame_lineno}</i>,\n    in <b>{frame_name}</b>\n    <span class=\"collapse-btn\" data-frame-id=\"{frame_filename}-{frame_lineno}\" onclick=\"collapse(this)\">{collapse_button}</span>\n    </p>\n    <div id=\"{frame_filename}-{frame_lineno}\" class=\"source-code {collapsed}\">{code_context}</div>\n</div>\n\"\"\"  # noqa: E501\n\nLINE = \"\"\"\n<p><span class=\"frame-line\">\n<span class=\"lineno\">{lineno}.</span> {line}</span></p>\n\"\"\"\n\nCENTER_LINE = \"\"\"\n<p class=\"center-line\"><span class=\"frame-line center-line\">\n<span class=\"lineno\">{lineno}.</span> {line}</span></p>\n\"\"\"\n\n\nclass ServerErrorMiddleware:\n    \"\"\"\n    Handles returning 500 responses when a server error occurs.\n\n    If 'debug' is set, then traceback responses will be returned,\n    otherwise the designated 'handler' will be called.\n\n    This middleware class should generally be used to wrap *everything*\n    else up, so that unhandled exceptions anywhere in the stack\n    always result in an appropriate 500 response.\n    \"\"\"\n\n    def __init__(\n        self, app: ASGIApp, handler: typing.Callable = None, debug: bool = False\n    ) -> None:\n        self.app = app\n        self.handler = handler\n        self.debug = debug\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        if scope[\"type\"] != \"http\":\n            await self.app(scope, receive, send)\n            return\n\n        response_started = False\n\n        async def _send(message: Message) -> None:\n            nonlocal response_started, send\n\n            if message[\"type\"] == \"http.response.start\":\n                response_started = True\n            await send(message)\n\n        try:\n            await self.app(scope, receive, _send)\n        except Exception as exc:\n            if not response_started:\n                request = Request(scope)\n                if self.debug:\n                    # In debug mode, return traceback responses.\n                    response = self.debug_response(request, exc)\n                elif self.handler is None:\n                    # Use our default 500 error handler.\n                    response = self.error_response(request, exc)\n                else:\n                    # Use an installed 500 error handler.\n                    if asyncio.iscoroutinefunction(self.handler):\n                        response = await self.handler(request, exc)\n                    else:\n                        response = await run_in_threadpool(self.handler, request, exc)\n\n                await response(scope, receive, send)\n\n            # We always continue to raise the exception.\n            # This allows servers to log the error, or allows test clients\n            # to optionally raise the error within the test case.\n            raise exc\n\n    def format_line(\n        self, index: int, line: str, frame_lineno: int, frame_index: int\n    ) -> str:\n        values = {\n            # HTML escape - line could contain < or >\n            \"line\": html.escape(line).replace(\" \", \"&nbsp\"),\n            \"lineno\": (frame_lineno - frame_index) + index,\n        }\n\n        if index != frame_index:\n            return LINE.format(**values)\n        return CENTER_LINE.format(**values)\n\n    def generate_frame_html(self, frame: inspect.FrameInfo, is_collapsed: bool) -> str:\n        code_context = \"\".join(\n            self.format_line(index, line, frame.lineno, frame.index)  # type: ignore\n            for index, line in enumerate(frame.code_context or [])\n        )\n\n        values = {\n            # HTML escape - filename could contain < or >, especially if it's a virtual\n            # file e.g. <stdin> in the REPL\n            \"frame_filename\": html.escape(frame.filename),\n            \"frame_lineno\": frame.lineno,\n            # HTML escape - if you try very hard it's possible to name a function with <\n            # or >\n            \"frame_name\": html.escape(frame.function),\n            \"code_context\": code_context,\n            \"collapsed\": \"collapsed\" if is_collapsed else \"\",\n            \"collapse_button\": \"+\" if is_collapsed else \"&#8210;\",\n        }\n        return FRAME_TEMPLATE.format(**values)\n\n    def generate_html(self, exc: Exception, limit: int = 7) -> str:\n        traceback_obj = traceback.TracebackException.from_exception(\n            exc, capture_locals=True\n        )\n\n        exc_html = \"\"\n        is_collapsed = False\n        exc_traceback = exc.__traceback__\n        if exc_traceback is not None:\n            frames = inspect.getinnerframes(exc_traceback, limit)\n            for frame in reversed(frames):\n                exc_html += self.generate_frame_html(frame, is_collapsed)\n                is_collapsed = True\n\n        # escape error class and text\n        error = (\n            f\"{html.escape(traceback_obj.exc_type.__name__)}: \"\n            f\"{html.escape(str(traceback_obj))}\"\n        )\n\n        return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)\n\n    def generate_plain_text(self, exc: Exception) -> str:\n        return \"\".join(traceback.format_exception(type(exc), exc, exc.__traceback__))\n\n    def debug_response(self, request: Request, exc: Exception) -> Response:\n        accept = request.headers.get(\"accept\", \"\")\n\n        if \"text/html\" in accept:\n            content = self.generate_html(exc)\n            return HTMLResponse(content, status_code=500)\n        content = self.generate_plain_text(exc)\n        return PlainTextResponse(content, status_code=500)\n\n    def error_response(self, request: Request, exc: Exception) -> Response:\n        return PlainTextResponse(\"Internal Server Error\", status_code=500)\n", "path": "starlette/middleware/errors.py"}], "after_files": [{"content": "import asyncio\nimport html\nimport inspect\nimport traceback\nimport typing\n\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, PlainTextResponse, Response\nfrom starlette.types import ASGIApp, Message, Receive, Scope, Send\n\nSTYLES = \"\"\"\np {\n    color: #211c1c;\n}\n.traceback-container {\n    border: 1px solid #038BB8;\n}\n.traceback-title {\n    background-color: #038BB8;\n    color: lemonchiffon;\n    padding: 12px;\n    font-size: 20px;\n    margin-top: 0px;\n}\n.frame-line {\n    padding-left: 10px;\n    font-family: monospace;\n}\n.frame-filename {\n    font-family: monospace;\n}\n.center-line {\n    background-color: #038BB8;\n    color: #f9f6e1;\n    padding: 5px 0px 5px 5px;\n}\n.lineno {\n    margin-right: 5px;\n}\n.frame-title {\n    font-weight: unset;\n    padding: 10px 10px 10px 10px;\n    background-color: #E4F4FD;\n    margin-right: 10px;\n    color: #191f21;\n    font-size: 17px;\n    border: 1px solid #c7dce8;\n}\n.collapse-btn {\n    float: right;\n    padding: 0px 5px 1px 5px;\n    border: solid 1px #96aebb;\n    cursor: pointer;\n}\n.collapsed {\n  display: none;\n}\n.source-code {\n  font-family: courier;\n  font-size: small;\n  padding-bottom: 10px;\n}\n\"\"\"\n\nJS = \"\"\"\n<script type=\"text/javascript\">\n    function collapse(element){\n        const frameId = element.getAttribute(\"data-frame-id\");\n        const frame = document.getElementById(frameId);\n\n        if (frame.classList.contains(\"collapsed\")){\n            element.innerHTML = \"&#8210;\";\n            frame.classList.remove(\"collapsed\");\n        } else {\n            element.innerHTML = \"+\";\n            frame.classList.add(\"collapsed\");\n        }\n    }\n</script>\n\"\"\"\n\nTEMPLATE = \"\"\"\n<html>\n    <head>\n        <style type='text/css'>\n            {styles}\n        </style>\n        <title>Starlette Debugger</title>\n    </head>\n    <body>\n        <h1>500 Server Error</h1>\n        <h2>{error}</h2>\n        <div class=\"traceback-container\">\n            <p class=\"traceback-title\">Traceback</p>\n            <div>{exc_html}</div>\n        </div>\n        {js}\n    </body>\n</html>\n\"\"\"\n\nFRAME_TEMPLATE = \"\"\"\n<div>\n    <p class=\"frame-title\">File <span class=\"frame-filename\">{frame_filename}</span>,\n    line <i>{frame_lineno}</i>,\n    in <b>{frame_name}</b>\n    <span class=\"collapse-btn\" data-frame-id=\"{frame_filename}-{frame_lineno}\" onclick=\"collapse(this)\">{collapse_button}</span>\n    </p>\n    <div id=\"{frame_filename}-{frame_lineno}\" class=\"source-code {collapsed}\">{code_context}</div>\n</div>\n\"\"\"  # noqa: E501\n\nLINE = \"\"\"\n<p><span class=\"frame-line\">\n<span class=\"lineno\">{lineno}.</span> {line}</span></p>\n\"\"\"\n\nCENTER_LINE = \"\"\"\n<p class=\"center-line\"><span class=\"frame-line center-line\">\n<span class=\"lineno\">{lineno}.</span> {line}</span></p>\n\"\"\"\n\n\nclass ServerErrorMiddleware:\n    \"\"\"\n    Handles returning 500 responses when a server error occurs.\n\n    If 'debug' is set, then traceback responses will be returned,\n    otherwise the designated 'handler' will be called.\n\n    This middleware class should generally be used to wrap *everything*\n    else up, so that unhandled exceptions anywhere in the stack\n    always result in an appropriate 500 response.\n    \"\"\"\n\n    def __init__(\n        self, app: ASGIApp, handler: typing.Callable = None, debug: bool = False\n    ) -> None:\n        self.app = app\n        self.handler = handler\n        self.debug = debug\n\n    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n        if scope[\"type\"] != \"http\":\n            await self.app(scope, receive, send)\n            return\n\n        response_started = False\n\n        async def _send(message: Message) -> None:\n            nonlocal response_started, send\n\n            if message[\"type\"] == \"http.response.start\":\n                response_started = True\n            await send(message)\n\n        try:\n            await self.app(scope, receive, _send)\n        except Exception as exc:\n            request = Request(scope)\n            if self.debug:\n                # In debug mode, return traceback responses.\n                response = self.debug_response(request, exc)\n            elif self.handler is None:\n                # Use our default 500 error handler.\n                response = self.error_response(request, exc)\n            else:\n                # Use an installed 500 error handler.\n                if asyncio.iscoroutinefunction(self.handler):\n                    response = await self.handler(request, exc)\n                else:\n                    response = await run_in_threadpool(self.handler, request, exc)\n\n            if not response_started:\n                await response(scope, receive, send)\n\n            # We always continue to raise the exception.\n            # This allows servers to log the error, or allows test clients\n            # to optionally raise the error within the test case.\n            raise exc\n\n    def format_line(\n        self, index: int, line: str, frame_lineno: int, frame_index: int\n    ) -> str:\n        values = {\n            # HTML escape - line could contain < or >\n            \"line\": html.escape(line).replace(\" \", \"&nbsp\"),\n            \"lineno\": (frame_lineno - frame_index) + index,\n        }\n\n        if index != frame_index:\n            return LINE.format(**values)\n        return CENTER_LINE.format(**values)\n\n    def generate_frame_html(self, frame: inspect.FrameInfo, is_collapsed: bool) -> str:\n        code_context = \"\".join(\n            self.format_line(index, line, frame.lineno, frame.index)  # type: ignore\n            for index, line in enumerate(frame.code_context or [])\n        )\n\n        values = {\n            # HTML escape - filename could contain < or >, especially if it's a virtual\n            # file e.g. <stdin> in the REPL\n            \"frame_filename\": html.escape(frame.filename),\n            \"frame_lineno\": frame.lineno,\n            # HTML escape - if you try very hard it's possible to name a function with <\n            # or >\n            \"frame_name\": html.escape(frame.function),\n            \"code_context\": code_context,\n            \"collapsed\": \"collapsed\" if is_collapsed else \"\",\n            \"collapse_button\": \"+\" if is_collapsed else \"&#8210;\",\n        }\n        return FRAME_TEMPLATE.format(**values)\n\n    def generate_html(self, exc: Exception, limit: int = 7) -> str:\n        traceback_obj = traceback.TracebackException.from_exception(\n            exc, capture_locals=True\n        )\n\n        exc_html = \"\"\n        is_collapsed = False\n        exc_traceback = exc.__traceback__\n        if exc_traceback is not None:\n            frames = inspect.getinnerframes(exc_traceback, limit)\n            for frame in reversed(frames):\n                exc_html += self.generate_frame_html(frame, is_collapsed)\n                is_collapsed = True\n\n        # escape error class and text\n        error = (\n            f\"{html.escape(traceback_obj.exc_type.__name__)}: \"\n            f\"{html.escape(str(traceback_obj))}\"\n        )\n\n        return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)\n\n    def generate_plain_text(self, exc: Exception) -> str:\n        return \"\".join(traceback.format_exception(type(exc), exc, exc.__traceback__))\n\n    def debug_response(self, request: Request, exc: Exception) -> Response:\n        accept = request.headers.get(\"accept\", \"\")\n\n        if \"text/html\" in accept:\n            content = self.generate_html(exc)\n            return HTMLResponse(content, status_code=500)\n        content = self.generate_plain_text(exc)\n        return PlainTextResponse(content, status_code=500)\n\n    def error_response(self, request: Request, exc: Exception) -> Response:\n        return PlainTextResponse(\"Internal Server Error\", status_code=500)\n", "path": "starlette/middleware/errors.py"}]}