Mapping Exceptions To Idiomatic Http Responses In Lagom

In the last post we saw how Lagom provides us a default exception serializer out of the box to help us translate exceptions to appropriate HTTP responses in Json.

We also learnt how Lagom treats exception translations differently when in production and in development as part of it's built in error handling strategy. How it is only the instances and subclass instances of TransportException that Lagom considers safe to return the exception details of.

Evidently, as a pragmatic practice we should throw instances of TransportException and even map other exceptions to TransportException so as to convey exceptions in the most appropriate and consistent way to the consumers of our services when and where possible.

One such opportunity we see in translation of InvalidCommandException from persistent entities to BadRequest HTTP error response in our service implementations. Since InvalidCommandException is not a subclass implementation of TransportException, Lagom could be seen treating it as an internal server error in development and consequently with no details in production.

This could definitely be fixed in our service implementation by catching these exceptions and returning an appropriate TransportException instead.

Another such opportunity we see when we need to convey certain results as approparite HTTP responses, such as, "No Records Found".

Show Comments