Let's Build an API Together - Part 15

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

Let’s start talking about error handling in our API.

When we build an API over HTTP, we should use proper HTTP status codes for errors or warnings. They are there for a reason, and we can use them.

  • 404 - when the object, instance or resource was not found, return a 404
  • 201 - when the object was created, return it
  • 200 - for all successful requests
  • 422 - Unprocessable entity, when we receive an object, and it fails during validation, etc., return that.
  • 500 - internal server erro as fall back if we realy messed up
  • 401 - if the user access a resource but isn’t authentictaed yet
  • 403 - if the user is authenticated but has no rights on the requested resource, object, etc.

Also, when using JSON as the requests/response format, we should return more information in JSON format too along the error. Not necessarily for 404 or alike, but you will pretty much use it on a 422 and explain to the calling app what went wrong so it can display an appropriate message for the user.

The easiest way in Spring MVC and Spring Boot is to either use the @ExceptionHandler or the @ControllerAdvice annotations. The first is used on individual controllers and their parents, and the latter is a global handler. I covered both in Spring Boot: How To Get Started and Build a Microservice.