'Flask errorhandler(500) not working in production fine on local machine
The below works fine when running in debug mode on my local machine but deployed (nginx, guinicorn, flask) only the 400 route works, 500 Server errror's still appear to display the standard browser screen and not my rendered template.
I assume its something to do with my nginx setup? Any one had this happen before.
@schedule.errorhandler(400)
def err_404(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
return e
return render_template("schedule/404.html"), 404
@schedule.errorhandler(500)
def err_500(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
logger.error(e, exc_info=True)
return render_template("schedule/500.html")
I'm using blueprints and application factory and just to test, I've also used register_error_handler when creating the app with no luck still
def create_app(test_config=None, scheduler_run=True):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
with app.app_context() as app_cont:
app.register_error_handler(500, err_500)
app.register_error_handler(404, err_404)
........
in case it is nginx - the server block is as below.
server {
server_name localhost plshire.co.uk www.plshire.co.uk;
location / {
include proxy_params;
proxy_pass http://unix:/home/ubuntu/plshire/plshire.sock;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/plshire.co.uk/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/plshire.co.uk/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = jobs.plshire.co.uk) {
return 301 https://plshire.co.uk/jobs;
}
if ($host = www.plshire.co.uk) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = plshire.co.uk) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name localhost plshire.co.uk www.plshire.co.uk;
return 404; # managed by Certbot
}
Solution 1:[1]
Probably the problem is in the nginx configuration, try adding the following parameter to the config file:
proxy_intercept_errors on;
proxy_intercept_errors
Determines whether proxied responses with codes greater than or equal to 300 should be passed to a client or be intercepted and redirected to nginx for processing with the error_page directive.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matteo Pasini |
