0
0
Nginxdevops~5 mins

JSON error responses in Nginx - Commands & Configuration

Choose your learning style9 modes available
Introduction
When a website or API has a problem, it shows an error message. JSON error responses let servers send error details in a simple, easy-to-read format. This helps apps and users understand what went wrong.
When your API needs to tell clients about errors in a clear, structured way.
When you want to replace default HTML error pages with JSON messages for easier app handling.
When building web services that communicate with mobile or frontend apps expecting JSON.
When debugging API issues and you want consistent error formats.
When you want to customize error messages for different HTTP status codes.
Config File - nginx.conf
nginx.conf
server {
    listen 8080;
    server_name localhost;

    location / {
        root /usr/share/nginx/html;
        index index.html;
    }

    error_page 404 = /json_404;
    error_page 500 502 503 504 = /json_50x;

    location = /json_404 {
        internal;
        default_type application/json;
        return 404 '{"error": "Not Found", "code": 404, "message": "The requested resource was not found."}';
    }

    location = /json_50x {
        internal;
        default_type application/json;
        return 500 '{"error": "Server Error", "code": 500, "message": "An internal server error occurred."}';
    }
}

This config listens on port 8080 and serves files from the default nginx html folder.

The error_page directives catch errors like 404 and 500-series and redirect them internally to special locations.

These special locations return JSON-formatted error messages with the correct HTTP status code and content type.

Commands
Check the nginx configuration file for syntax errors before restarting the server.
Terminal
nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Restart the nginx service to apply the new configuration with JSON error responses.
Terminal
systemctl restart nginx
Expected OutputExpected
No output (command runs silently)
Request a missing page to see the JSON 404 error response from nginx.
Terminal
curl -i http://localhost:8080/nonexistent
Expected OutputExpected
HTTP/1.1 404 Not Found Server: nginx/1.24.0 Date: Thu, 01 Jun 2024 12:00:00 GMT Content-Type: application/json Content-Length: 72 Connection: keep-alive {"error": "Not Found", "code": 404, "message": "The requested resource was not found."}
Simulate a server error to see the JSON 500 error response (you may need to configure a route that triggers 500).
Terminal
curl -i http://localhost:8080/internal_error
Expected OutputExpected
HTTP/1.1 500 Internal Server Error Server: nginx/1.24.0 Date: Thu, 01 Jun 2024 12:00:00 GMT Content-Type: application/json Content-Length: 69 Connection: keep-alive {"error": "Server Error", "code": 500, "message": "An internal server error occurred."}
Key Concept

If you remember nothing else from this pattern, remember: nginx can send clear JSON error messages by redirecting error codes to internal locations that return JSON responses.

Common Mistakes
Not setting the content type to application/json in the error response location.
Clients may not recognize the response as JSON and fail to parse it correctly.
Always include 'default_type application/json;' in the error response location block.
Using external redirects instead of internal redirects for error_page.
External redirects change the URL and may confuse clients or cause extra requests.
Use internal redirects with '=' in error_page to keep the URL unchanged and serve JSON directly.
Not testing nginx configuration before restart.
Syntax errors can cause nginx to fail restarting, leading to downtime.
Always run 'nginx -t' to verify config syntax before restarting.
Summary
Configure nginx error_page directives to redirect error codes to internal JSON response locations.
Set the content type to application/json and return JSON-formatted error messages with the correct HTTP status.
Test the configuration syntax and restart nginx to apply changes, then verify JSON error responses with curl.