Let's Build an API Together - Part 16

Last Update: 10.01.2018. By Jens in API Series | APIs | Newsletter

Last time we talked about using proper HTTP status codes and also returning errors in a JSON format back to the client.

What we should never expose to a client or customer are Java stack traces. Nobody should see them, except you devs. The easiest way to prevent these in Spring MVC is to add a global exception handler with a @ControllerAdvice and catch all Exception.

We also talked about returning more info in exchange format of the API, probably JSON. When we run simple validations or complex business logic, we should return proper information to the client. What worked well for me was to use message codes in the response and not plain text. The payload is smaller, and you can leave it to the client how it explains the message to the users; also prevents to have localization in the API just for error messages.

To keep an up-to-date overview of all the messages in the application, it worked damn good for me to declare them in an enum. The enum also implements an interface which makes it easy in a CI build to find all messages code enums in the code base, extract them and, e.g., publish them to a wiki page or for further processing by another team for providing the actual text.

Such an enum has at least two fields, usually three. It contains a unique ID of the component/service it belongs too, a unique ID (inside the component) for a particular error/message and a short explanation in English for the devs, which can also be used as a base for the translator or texter later.