Search code examples
springmessagingspring-cloud-stream

How return a Message (from Spring) to represent that the information was not found?


I'm working with messaging on Spring and I had a simple question.

When another services sends a message requesting an information that does not exists for the service that are able to answer, the first thing that I thoutght was pass a "null" do the payload:

MyResponse myResponse = service.find(id); //ops, the information with this id does not exists

Message<MyResponse> message = MessageBuilder
        .withPayload(myResponse) // the information does not exists, so null
        .copyHeadersIfAbsent(request.getHeaders())
        .build();

But the method withPayload not accept null. So, what is the good practice or alternative to fill this message with a "empty" value to the original request receive the result and know that this information does not exists?

For now I'm passing a empty object (new MyResponse()) to the payload, but this could create a confusion for who consumes the message. I could create another class to represent this "not exists" state, but I'm trying to understand my options now.

Thanks!


Solution

  • The null payload doesn't bring too much information and isn't supported by many network protocols. More over there are many places in the framework which are based on the payload type, but if it is a null we might not have any information what and how to do with it. In some components the null return value is a signal to stop the flow and don't produce any messages downstream to reply.

    The solution you may go is like constant object (MyNullResponse) to indicate that it is about a null.

    You might also consider a way with an exception instead of an attempt to return null. Let's consider that you do some post-search processing and a bunch of filtering and conversion steps. In case of null your message will still travel all the flow down. But when we deal with an exception (like it is with the javax.persistence.EntityNotFoundException) we just bubble the problem to end-user immediately. And that's already the target service responsibility to represent that exception as a comprehensible message for end-user.

    We have a JIRA ticket about null payload support. You can read there about more reasons and what other people think on the matter. My idea to allow something on the matter is like Optional.empty(). Then we can map it to null easily on the target end-user code.