Cover by Subbu Allamaraju

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

3.13. How to Return Errors

HTTP is based on the exchange of representations, and that applies to errors as well. When a server encounters an error, either because of problems with the request that a client submitted or because of problems within the server, always return a representation that reflects the state of the error condition. This includes the response status code, response headers, and a body containing the description of the error.

Problem

You want to know how to return errors to clients.

Solution

For errors due to client inputs, return a representation with a 4xx status code. For errors due to server implementation or its current state, return a representation with a 5xx status code. In both cases, include a Date header with a value indicating the date-time at which the error occurred.

Unless the request method is HEAD, include a body in the representation formatted and localized using content negotiation (see Chapter 7) or in human-readable HTML or plain text.

If information to correct or debug the error is available as a separate human-readable document, include a link to that document via a Link header (see Recipe 5.3) or a link in the body.

If you are logging errors on the server side for later tracking or analysis, provide an identifier or a link that can be used to refer to that error. For instance, clients can report the error code to the server’s team while reporting problems.

Keep the response body descriptive, but exclude details such as stack traces, errors from database ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required