Improve error messages on simple after request hook bugs
zx80 opened this issue · 1 comments
zx80 commented
When a user forgets to return the response in an after_request
hook, the message is particularly unhelpful as it does not point to the involvement of the hook:
from flask import Flask
app = Flask("test")
# oops
app.after_request(lambda _: None)
@app.get("/hello")
def get_hello():
return "hello world!", 200
Run:
flask --debug -A app run
curl -si -X GET http://0.0.0.0:5000/hello
Results in:
TypeError
TypeError: 'NoneType' object is not callable
Traceback (most recent call last)
File "/home/fabien/tmp/test/venv/lib/python3.12/site-packages/flask/app.py", line 1478, in __call__
return self.wsgi_app(environ, start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/fabien/tmp/test/venv/lib/python3.12/site-packages/flask/app.py", line 1462, in wsgi_app
return response(environ, start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not callable
I suggest that the error message should point to the involvement of the after request hook.
davidism commented
I'm hesitant to do this at runtime. It would require checking the return value of every after_request
function call for every request, overhead that isn't necessary if things are written correctly. This check would also run away from where the function was defined or registered, so the traceback wouldn't be any more useful. This is something type checking should pick up, because after_request
functions should be annotated to return a response.