We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Reloading sometimes gives a TypeError: 'NoneType' object is not callable
I'm running a custom app (subclass of `BaseApplication`) with reload set to True. In some situations, changing a file causes the following traceback:

```
Exception in thread Thread-1 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
  File "/usr/maxm/lib/python2.7/threading.py", line 551, in __bootstrap_inner
  File "/usr/maxm/lib/python2.7/site-packages/gunicorn/reloader.py", line 52, in run
  File "/usr/maxm/lib/python2.7/site-packages/gunicorn/workers/base.py", line 87, in changed
<type 'exceptions.TypeError'>: 'NoneType' object is not callable
```

It's intermittent; I can sometimes reproduce it several times in a row by touching the same file, and then it stops happening. It certainly doesn't seem to interfere with the reloading behavior.

Line 87 is only `raise SystemExit()`. But line 86 is `os.kill(self.pid, signal.SIGQUIT)`, so I think what's happening is that the interpreter has started to tear down the environment and `SystemExit` has become `None`. (See also [this](http://article.gmane.org/gmane.comp.python.general/387087/) mailing list post.) 

Anything I can do about this?


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `gunicorn/workers/base.py`
Content:
```
1 # -*- coding: utf-8 -
2 #
3 # This file is part of gunicorn released under the MIT license.
4 # See the NOTICE for more information.
5 
6 from datetime import datetime
7 import os
8 import signal
9 import sys
10 from random import randint
11 
12 
13 from gunicorn import util
14 from gunicorn.workers.workertmp import WorkerTmp
15 from gunicorn.reloader import Reloader
16 from gunicorn.http.errors import (
17     InvalidHeader, InvalidHeaderName, InvalidRequestLine, InvalidRequestMethod,
18     InvalidHTTPVersion, LimitRequestLine, LimitRequestHeaders,
19 )
20 from gunicorn.http.errors import InvalidProxyLine, ForbiddenProxyRequest
21 from gunicorn.http.wsgi import default_environ, Response
22 from gunicorn.six import MAXSIZE
23 
24 
25 class Worker(object):
26 
27     SIGNALS = [getattr(signal, "SIG%s" % x)
28             for x in "ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD".split()]
29 
30     PIPE = []
31 
32     def __init__(self, age, ppid, sockets, app, timeout, cfg, log):
33         """\
34         This is called pre-fork so it shouldn't do anything to the
35         current process. If there's a need to make process wide
36         changes you'll want to do that in ``self.init_process()``.
37         """
38         self.age = age
39         self.ppid = ppid
40         self.sockets = sockets
41         self.app = app
42         self.timeout = timeout
43         self.cfg = cfg
44         self.booted = False
45         self.aborted = False
46 
47         self.nr = 0
48         jitter = randint(0, cfg.max_requests_jitter)
49         self.max_requests = cfg.max_requests + jitter or MAXSIZE
50         self.alive = True
51         self.log = log
52         self.tmp = WorkerTmp(cfg)
53 
54     def __str__(self):
55         return "<Worker %s>" % self.pid
56 
57     @property
58     def pid(self):
59         return os.getpid()
60 
61     def notify(self):
62         """\
63         Your worker subclass must arrange to have this method called
64         once every ``self.timeout`` seconds. If you fail in accomplishing
65         this task, the master process will murder your workers.
66         """
67         self.tmp.notify()
68 
69     def run(self):
70         """\
71         This is the mainloop of a worker process. You should override
72         this method in a subclass to provide the intended behaviour
73         for your particular evil schemes.
74         """
75         raise NotImplementedError()
76 
77     def init_process(self):
78         """\
79         If you override this method in a subclass, the last statement
80         in the function should be to call this method with
81         super(MyWorkerClass, self).init_process() so that the ``run()``
82         loop is initiated.
83         """
84 
85         # start the reloader
86         if self.cfg.reload:
87             def changed(fname):
88                 self.log.info("Worker reloading: %s modified", fname)
89                 os.kill(self.pid, signal.SIGQUIT)
90                 raise SystemExit()
91             Reloader(callback=changed).start()
92 
93         # set environment' variables
94         if self.cfg.env:
95             for k, v in self.cfg.env.items():
96                 os.environ[k] = v
97 
98         util.set_owner_process(self.cfg.uid, self.cfg.gid)
99 
100         # Reseed the random number generator
101         util.seed()
102 
103         # For waking ourselves up
104         self.PIPE = os.pipe()
105         for p in self.PIPE:
106             util.set_non_blocking(p)
107             util.close_on_exec(p)
108 
109         # Prevent fd inheritance
110         [util.close_on_exec(s) for s in self.sockets]
111         util.close_on_exec(self.tmp.fileno())
112 
113         self.log.close_on_exec()
114 
115         self.init_signals()
116 
117         self.wsgi = self.app.wsgi()
118 
119         self.cfg.post_worker_init(self)
120 
121         # Enter main run loop
122         self.booted = True
123         self.run()
124 
125     def init_signals(self):
126         # reset signaling
127         [signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]
128         # init new signaling
129         signal.signal(signal.SIGQUIT, self.handle_quit)
130         signal.signal(signal.SIGTERM, self.handle_exit)
131         signal.signal(signal.SIGINT, self.handle_quit)
132         signal.signal(signal.SIGWINCH, self.handle_winch)
133         signal.signal(signal.SIGUSR1, self.handle_usr1)
134         signal.signal(signal.SIGABRT, self.handle_abort)
135 
136         # Don't let SIGTERM and SIGUSR1 disturb active requests
137         # by interrupting system calls
138         if hasattr(signal, 'siginterrupt'):  # python >= 2.6
139             signal.siginterrupt(signal.SIGTERM, False)
140             signal.siginterrupt(signal.SIGUSR1, False)
141 
142     def handle_usr1(self, sig, frame):
143         self.log.reopen_files()
144 
145     def handle_exit(self, sig, frame):
146         self.alive = False
147 
148     def handle_quit(self, sig, frame):
149         self.alive = False
150         # worker_int callback
151         self.cfg.worker_int(self)
152         sys.exit(0)
153 
154     def handle_abort(self, sig, frame):
155         self.alive = False
156         self.cfg.worker_abort(self)
157         sys.exit(1)
158 
159     def handle_error(self, req, client, addr, exc):
160         request_start = datetime.now()
161         addr = addr or ('', -1)  # unix socket case
162         if isinstance(exc, (InvalidRequestLine, InvalidRequestMethod,
163                 InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,
164                 LimitRequestLine, LimitRequestHeaders,
165                 InvalidProxyLine, ForbiddenProxyRequest)):
166 
167             status_int = 400
168             reason = "Bad Request"
169 
170             if isinstance(exc, InvalidRequestLine):
171                 mesg = "Invalid Request Line '%s'" % str(exc)
172             elif isinstance(exc, InvalidRequestMethod):
173                 mesg = "Invalid Method '%s'" % str(exc)
174             elif isinstance(exc, InvalidHTTPVersion):
175                 mesg = "Invalid HTTP Version '%s'" % str(exc)
176             elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)):
177                 mesg = "%s" % str(exc)
178                 if not req and hasattr(exc, "req"):
179                     req = exc.req  # for access log
180             elif isinstance(exc, LimitRequestLine):
181                 mesg = "%s" % str(exc)
182             elif isinstance(exc, LimitRequestHeaders):
183                 mesg = "Error parsing headers: '%s'" % str(exc)
184             elif isinstance(exc, InvalidProxyLine):
185                 mesg = "'%s'" % str(exc)
186             elif isinstance(exc, ForbiddenProxyRequest):
187                 reason = "Forbidden"
188                 mesg = "Request forbidden"
189                 status_int = 403
190 
191             msg = "Invalid request from ip={ip}: {error}"
192             self.log.debug(msg.format(ip=addr[0], error=str(exc)))
193         else:
194             self.log.exception("Error handling request")
195 
196             status_int = 500
197             reason = "Internal Server Error"
198             mesg = ""
199 
200         if req is not None:
201             request_time = datetime.now() - request_start
202             environ = default_environ(req, client, self.cfg)
203             environ['REMOTE_ADDR'] = addr[0]
204             environ['REMOTE_PORT'] = str(addr[1])
205             resp = Response(req, client, self.cfg)
206             resp.status = "%s %s" % (status_int, reason)
207             resp.response_length = len(mesg)
208             self.log.access(resp, req, environ, request_time)
209 
210         try:
211             util.write_error(client, status_int, reason, mesg)
212         except:
213             self.log.debug("Failed to send error message.")
214 
215     def handle_winch(self, sig, fname):
216         # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.
217         return
218
```
--- 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/gunicorn/workers/base.py b/gunicorn/workers/base.py
--- a/gunicorn/workers/base.py
+++ b/gunicorn/workers/base.py
@@ -87,7 +87,6 @@
             def changed(fname):
                 self.log.info("Worker reloading: %s modified", fname)
                 os.kill(self.pid, signal.SIGQUIT)
-                raise SystemExit()
             Reloader(callback=changed).start()
 
         # set environment' variables

{"golden_diff": "diff --git a/gunicorn/workers/base.py b/gunicorn/workers/base.py\n--- a/gunicorn/workers/base.py\n+++ b/gunicorn/workers/base.py\n@@ -87,7 +87,6 @@\n             def changed(fname):\n                 self.log.info(\"Worker reloading: %s modified\", fname)\n                 os.kill(self.pid, signal.SIGQUIT)\n-                raise SystemExit()\n             Reloader(callback=changed).start()\n \n         # set environment' variables\n", "issue": "Reloading sometimes gives a TypeError: 'NoneType' object is not callable\nI'm running a custom app (subclass of `BaseApplication`) with reload set to True. In some situations, changing a file causes the following traceback:\n\n```\nException in thread Thread-1 (most likely raised during interpreter shutdown):\nTraceback (most recent call last):\n  File \"/usr/maxm/lib/python2.7/threading.py\", line 551, in __bootstrap_inner\n  File \"/usr/maxm/lib/python2.7/site-packages/gunicorn/reloader.py\", line 52, in run\n  File \"/usr/maxm/lib/python2.7/site-packages/gunicorn/workers/base.py\", line 87, in changed\n<type 'exceptions.TypeError'>: 'NoneType' object is not callable\n```\n\nIt's intermittent; I can sometimes reproduce it several times in a row by touching the same file, and then it stops happening. It certainly doesn't seem to interfere with the reloading behavior.\n\nLine 87 is only `raise SystemExit()`. But line 86 is `os.kill(self.pid, signal.SIGQUIT)`, so I think what's happening is that the interpreter has started to tear down the environment and `SystemExit` has become `None`. (See also [this](http://article.gmane.org/gmane.comp.python.general/387087/) mailing list post.) \n\nAnything I can do about this?\n\n", "before_files": [{"content": "# -*- coding: utf-8 -\n#\n# This file is part of gunicorn released under the MIT license.\n# See the NOTICE for more information.\n\nfrom datetime import datetime\nimport os\nimport signal\nimport sys\nfrom random import randint\n\n\nfrom gunicorn import util\nfrom gunicorn.workers.workertmp import WorkerTmp\nfrom gunicorn.reloader import Reloader\nfrom gunicorn.http.errors import (\n    InvalidHeader, InvalidHeaderName, InvalidRequestLine, InvalidRequestMethod,\n    InvalidHTTPVersion, LimitRequestLine, LimitRequestHeaders,\n)\nfrom gunicorn.http.errors import InvalidProxyLine, ForbiddenProxyRequest\nfrom gunicorn.http.wsgi import default_environ, Response\nfrom gunicorn.six import MAXSIZE\n\n\nclass Worker(object):\n\n    SIGNALS = [getattr(signal, \"SIG%s\" % x)\n            for x in \"ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD\".split()]\n\n    PIPE = []\n\n    def __init__(self, age, ppid, sockets, app, timeout, cfg, log):\n        \"\"\"\\\n        This is called pre-fork so it shouldn't do anything to the\n        current process. If there's a need to make process wide\n        changes you'll want to do that in ``self.init_process()``.\n        \"\"\"\n        self.age = age\n        self.ppid = ppid\n        self.sockets = sockets\n        self.app = app\n        self.timeout = timeout\n        self.cfg = cfg\n        self.booted = False\n        self.aborted = False\n\n        self.nr = 0\n        jitter = randint(0, cfg.max_requests_jitter)\n        self.max_requests = cfg.max_requests + jitter or MAXSIZE\n        self.alive = True\n        self.log = log\n        self.tmp = WorkerTmp(cfg)\n\n    def __str__(self):\n        return \"<Worker %s>\" % self.pid\n\n    @property\n    def pid(self):\n        return os.getpid()\n\n    def notify(self):\n        \"\"\"\\\n        Your worker subclass must arrange to have this method called\n        once every ``self.timeout`` seconds. If you fail in accomplishing\n        this task, the master process will murder your workers.\n        \"\"\"\n        self.tmp.notify()\n\n    def run(self):\n        \"\"\"\\\n        This is the mainloop of a worker process. You should override\n        this method in a subclass to provide the intended behaviour\n        for your particular evil schemes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def init_process(self):\n        \"\"\"\\\n        If you override this method in a subclass, the last statement\n        in the function should be to call this method with\n        super(MyWorkerClass, self).init_process() so that the ``run()``\n        loop is initiated.\n        \"\"\"\n\n        # start the reloader\n        if self.cfg.reload:\n            def changed(fname):\n                self.log.info(\"Worker reloading: %s modified\", fname)\n                os.kill(self.pid, signal.SIGQUIT)\n                raise SystemExit()\n            Reloader(callback=changed).start()\n\n        # set environment' variables\n        if self.cfg.env:\n            for k, v in self.cfg.env.items():\n                os.environ[k] = v\n\n        util.set_owner_process(self.cfg.uid, self.cfg.gid)\n\n        # Reseed the random number generator\n        util.seed()\n\n        # For waking ourselves up\n        self.PIPE = os.pipe()\n        for p in self.PIPE:\n            util.set_non_blocking(p)\n            util.close_on_exec(p)\n\n        # Prevent fd inheritance\n        [util.close_on_exec(s) for s in self.sockets]\n        util.close_on_exec(self.tmp.fileno())\n\n        self.log.close_on_exec()\n\n        self.init_signals()\n\n        self.wsgi = self.app.wsgi()\n\n        self.cfg.post_worker_init(self)\n\n        # Enter main run loop\n        self.booted = True\n        self.run()\n\n    def init_signals(self):\n        # reset signaling\n        [signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]\n        # init new signaling\n        signal.signal(signal.SIGQUIT, self.handle_quit)\n        signal.signal(signal.SIGTERM, self.handle_exit)\n        signal.signal(signal.SIGINT, self.handle_quit)\n        signal.signal(signal.SIGWINCH, self.handle_winch)\n        signal.signal(signal.SIGUSR1, self.handle_usr1)\n        signal.signal(signal.SIGABRT, self.handle_abort)\n\n        # Don't let SIGTERM and SIGUSR1 disturb active requests\n        # by interrupting system calls\n        if hasattr(signal, 'siginterrupt'):  # python >= 2.6\n            signal.siginterrupt(signal.SIGTERM, False)\n            signal.siginterrupt(signal.SIGUSR1, False)\n\n    def handle_usr1(self, sig, frame):\n        self.log.reopen_files()\n\n    def handle_exit(self, sig, frame):\n        self.alive = False\n\n    def handle_quit(self, sig, frame):\n        self.alive = False\n        # worker_int callback\n        self.cfg.worker_int(self)\n        sys.exit(0)\n\n    def handle_abort(self, sig, frame):\n        self.alive = False\n        self.cfg.worker_abort(self)\n        sys.exit(1)\n\n    def handle_error(self, req, client, addr, exc):\n        request_start = datetime.now()\n        addr = addr or ('', -1)  # unix socket case\n        if isinstance(exc, (InvalidRequestLine, InvalidRequestMethod,\n                InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,\n                LimitRequestLine, LimitRequestHeaders,\n                InvalidProxyLine, ForbiddenProxyRequest)):\n\n            status_int = 400\n            reason = \"Bad Request\"\n\n            if isinstance(exc, InvalidRequestLine):\n                mesg = \"Invalid Request Line '%s'\" % str(exc)\n            elif isinstance(exc, InvalidRequestMethod):\n                mesg = \"Invalid Method '%s'\" % str(exc)\n            elif isinstance(exc, InvalidHTTPVersion):\n                mesg = \"Invalid HTTP Version '%s'\" % str(exc)\n            elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)):\n                mesg = \"%s\" % str(exc)\n                if not req and hasattr(exc, \"req\"):\n                    req = exc.req  # for access log\n            elif isinstance(exc, LimitRequestLine):\n                mesg = \"%s\" % str(exc)\n            elif isinstance(exc, LimitRequestHeaders):\n                mesg = \"Error parsing headers: '%s'\" % str(exc)\n            elif isinstance(exc, InvalidProxyLine):\n                mesg = \"'%s'\" % str(exc)\n            elif isinstance(exc, ForbiddenProxyRequest):\n                reason = \"Forbidden\"\n                mesg = \"Request forbidden\"\n                status_int = 403\n\n            msg = \"Invalid request from ip={ip}: {error}\"\n            self.log.debug(msg.format(ip=addr[0], error=str(exc)))\n        else:\n            self.log.exception(\"Error handling request\")\n\n            status_int = 500\n            reason = \"Internal Server Error\"\n            mesg = \"\"\n\n        if req is not None:\n            request_time = datetime.now() - request_start\n            environ = default_environ(req, client, self.cfg)\n            environ['REMOTE_ADDR'] = addr[0]\n            environ['REMOTE_PORT'] = str(addr[1])\n            resp = Response(req, client, self.cfg)\n            resp.status = \"%s %s\" % (status_int, reason)\n            resp.response_length = len(mesg)\n            self.log.access(resp, req, environ, request_time)\n\n        try:\n            util.write_error(client, status_int, reason, mesg)\n        except:\n            self.log.debug(\"Failed to send error message.\")\n\n    def handle_winch(self, sig, fname):\n        # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.\n        return\n", "path": "gunicorn/workers/base.py"}], "after_files": [{"content": "# -*- coding: utf-8 -\n#\n# This file is part of gunicorn released under the MIT license.\n# See the NOTICE for more information.\n\nfrom datetime import datetime\nimport os\nimport signal\nimport sys\nfrom random import randint\n\n\nfrom gunicorn import util\nfrom gunicorn.workers.workertmp import WorkerTmp\nfrom gunicorn.reloader import Reloader\nfrom gunicorn.http.errors import (\n    InvalidHeader, InvalidHeaderName, InvalidRequestLine, InvalidRequestMethod,\n    InvalidHTTPVersion, LimitRequestLine, LimitRequestHeaders,\n)\nfrom gunicorn.http.errors import InvalidProxyLine, ForbiddenProxyRequest\nfrom gunicorn.http.wsgi import default_environ, Response\nfrom gunicorn.six import MAXSIZE\n\n\nclass Worker(object):\n\n    SIGNALS = [getattr(signal, \"SIG%s\" % x)\n            for x in \"ABRT HUP QUIT INT TERM USR1 USR2 WINCH CHLD\".split()]\n\n    PIPE = []\n\n    def __init__(self, age, ppid, sockets, app, timeout, cfg, log):\n        \"\"\"\\\n        This is called pre-fork so it shouldn't do anything to the\n        current process. If there's a need to make process wide\n        changes you'll want to do that in ``self.init_process()``.\n        \"\"\"\n        self.age = age\n        self.ppid = ppid\n        self.sockets = sockets\n        self.app = app\n        self.timeout = timeout\n        self.cfg = cfg\n        self.booted = False\n        self.aborted = False\n\n        self.nr = 0\n        jitter = randint(0, cfg.max_requests_jitter)\n        self.max_requests = cfg.max_requests + jitter or MAXSIZE\n        self.alive = True\n        self.log = log\n        self.tmp = WorkerTmp(cfg)\n\n    def __str__(self):\n        return \"<Worker %s>\" % self.pid\n\n    @property\n    def pid(self):\n        return os.getpid()\n\n    def notify(self):\n        \"\"\"\\\n        Your worker subclass must arrange to have this method called\n        once every ``self.timeout`` seconds. If you fail in accomplishing\n        this task, the master process will murder your workers.\n        \"\"\"\n        self.tmp.notify()\n\n    def run(self):\n        \"\"\"\\\n        This is the mainloop of a worker process. You should override\n        this method in a subclass to provide the intended behaviour\n        for your particular evil schemes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def init_process(self):\n        \"\"\"\\\n        If you override this method in a subclass, the last statement\n        in the function should be to call this method with\n        super(MyWorkerClass, self).init_process() so that the ``run()``\n        loop is initiated.\n        \"\"\"\n\n        # start the reloader\n        if self.cfg.reload:\n            def changed(fname):\n                self.log.info(\"Worker reloading: %s modified\", fname)\n                os.kill(self.pid, signal.SIGQUIT)\n            Reloader(callback=changed).start()\n\n        # set environment' variables\n        if self.cfg.env:\n            for k, v in self.cfg.env.items():\n                os.environ[k] = v\n\n        util.set_owner_process(self.cfg.uid, self.cfg.gid)\n\n        # Reseed the random number generator\n        util.seed()\n\n        # For waking ourselves up\n        self.PIPE = os.pipe()\n        for p in self.PIPE:\n            util.set_non_blocking(p)\n            util.close_on_exec(p)\n\n        # Prevent fd inheritance\n        [util.close_on_exec(s) for s in self.sockets]\n        util.close_on_exec(self.tmp.fileno())\n\n        self.log.close_on_exec()\n\n        self.init_signals()\n\n        self.wsgi = self.app.wsgi()\n\n        self.cfg.post_worker_init(self)\n\n        # Enter main run loop\n        self.booted = True\n        self.run()\n\n    def init_signals(self):\n        # reset signaling\n        [signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]\n        # init new signaling\n        signal.signal(signal.SIGQUIT, self.handle_quit)\n        signal.signal(signal.SIGTERM, self.handle_exit)\n        signal.signal(signal.SIGINT, self.handle_quit)\n        signal.signal(signal.SIGWINCH, self.handle_winch)\n        signal.signal(signal.SIGUSR1, self.handle_usr1)\n        signal.signal(signal.SIGABRT, self.handle_abort)\n\n        # Don't let SIGTERM and SIGUSR1 disturb active requests\n        # by interrupting system calls\n        if hasattr(signal, 'siginterrupt'):  # python >= 2.6\n            signal.siginterrupt(signal.SIGTERM, False)\n            signal.siginterrupt(signal.SIGUSR1, False)\n\n    def handle_usr1(self, sig, frame):\n        self.log.reopen_files()\n\n    def handle_exit(self, sig, frame):\n        self.alive = False\n\n    def handle_quit(self, sig, frame):\n        self.alive = False\n        # worker_int callback\n        self.cfg.worker_int(self)\n        sys.exit(0)\n\n    def handle_abort(self, sig, frame):\n        self.alive = False\n        self.cfg.worker_abort(self)\n        sys.exit(1)\n\n    def handle_error(self, req, client, addr, exc):\n        request_start = datetime.now()\n        addr = addr or ('', -1)  # unix socket case\n        if isinstance(exc, (InvalidRequestLine, InvalidRequestMethod,\n                InvalidHTTPVersion, InvalidHeader, InvalidHeaderName,\n                LimitRequestLine, LimitRequestHeaders,\n                InvalidProxyLine, ForbiddenProxyRequest)):\n\n            status_int = 400\n            reason = \"Bad Request\"\n\n            if isinstance(exc, InvalidRequestLine):\n                mesg = \"Invalid Request Line '%s'\" % str(exc)\n            elif isinstance(exc, InvalidRequestMethod):\n                mesg = \"Invalid Method '%s'\" % str(exc)\n            elif isinstance(exc, InvalidHTTPVersion):\n                mesg = \"Invalid HTTP Version '%s'\" % str(exc)\n            elif isinstance(exc, (InvalidHeaderName, InvalidHeader,)):\n                mesg = \"%s\" % str(exc)\n                if not req and hasattr(exc, \"req\"):\n                    req = exc.req  # for access log\n            elif isinstance(exc, LimitRequestLine):\n                mesg = \"%s\" % str(exc)\n            elif isinstance(exc, LimitRequestHeaders):\n                mesg = \"Error parsing headers: '%s'\" % str(exc)\n            elif isinstance(exc, InvalidProxyLine):\n                mesg = \"'%s'\" % str(exc)\n            elif isinstance(exc, ForbiddenProxyRequest):\n                reason = \"Forbidden\"\n                mesg = \"Request forbidden\"\n                status_int = 403\n\n            msg = \"Invalid request from ip={ip}: {error}\"\n            self.log.debug(msg.format(ip=addr[0], error=str(exc)))\n        else:\n            self.log.exception(\"Error handling request\")\n\n            status_int = 500\n            reason = \"Internal Server Error\"\n            mesg = \"\"\n\n        if req is not None:\n            request_time = datetime.now() - request_start\n            environ = default_environ(req, client, self.cfg)\n            environ['REMOTE_ADDR'] = addr[0]\n            environ['REMOTE_PORT'] = str(addr[1])\n            resp = Response(req, client, self.cfg)\n            resp.status = \"%s %s\" % (status_int, reason)\n            resp.response_length = len(mesg)\n            self.log.access(resp, req, environ, request_time)\n\n        try:\n            util.write_error(client, status_int, reason, mesg)\n        except:\n            self.log.debug(\"Failed to send error message.\")\n\n    def handle_winch(self, sig, fname):\n        # Ignore SIGWINCH in worker. Fixes a crash on OpenBSD.\n        return\n", "path": "gunicorn/workers/base.py"}]}