ExceptionSerializer
. This Knoldus blog post explains it well: https://blog.knoldus.com/2018/02/05/exception-serializer-in-lagom/ That example, however, is more focused on how to deserialize exceptions when communicating with external services. Here is an example of using it to serialize an exception to a custom response with status 422 and "text/plain" content-type:public class CustomExceptionSerializer implements ExceptionSerializer {
private final MessageProtocol MESSAGE_PROTOCOL = new MessageProtocol(
Optional.of("text/plain"),
Optional.of("utf-8"),
Optional.empty()
);
@Override
public RawExceptionMessage serialize(Throwable exception, Collection<MessageProtocol> accept) {
if (exception instanceof DeserializationException) {
return new RawExceptionMessage(
TransportErrorCode.fromHttp(422),
MESSAGE_PROTOCOL,
ByteString.fromString("Could not deserialize request body: " + exception.getMessage())
);
// } else if (exception instanceof ...) {
// handle more types here
} else {
return new RawExceptionMessage(
TransportErrorCode.InternalServerError,
MESSAGE_PROTOCOL,
ByteString.fromString("Exception: " + exception.getMessage())
);
}
}
@Override
public Throwable deserialize(RawExceptionMessage message) {
// Implement this if you also use a Lagom service client to handle errors on the client side
throw new UnsupportedOperationException("not implemented");
}
}
One important thing to be aware of is that this completely overrides the default exception serializer from Lagom, so your custom serializer will need to handle all of the exception types that your service might raise.