Home > Enterprise >  HTTP errors as json in nginx
HTTP errors as json in nginx

Time:03-07

I have Python Flask application that uses @app.errorhandler to return json a object instead of the typical HTML messages when occurrs a bad request, method not allowed, page not found or any other HTTP exception.

I am now trying to make nginx handle such things with only partial success. When I make a request using an invalid method (e.g. PATCH) I get the json message. But when I use an unexisting page, I get the typical HTML message.

This is how my nginx server configuration looks like. It is the example given in the Flask docs with two extra lines at the end:

server {
    location / {
        limit_except GET POST {
            deny all;
        }

        try_files $uri @yourapplication;
    }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/uwsgi.sock;
    }

    proxy_intercept_errors on;
    include api_json_errors.conf;
}

where api_json_errors.conf is something like this:

error_page 400 = @400;
location @400 { return 400 '{"status":400,"message":"Bad request"}\n'; }

CodePudding user response:

You have to use uwsgi_intercept_errors with uwsgi_pass

And proxy_intercept_errors with proxy_pass

  • Related