Search code examples
httpcachingballerina

How to cache an error response from http?


I am trying to add caching to the client side of an http call. The requirement is to cache the response of the http call to reuse them without calling the server every time. The server returns an record or an error as specified in the below code segment.

// http call
SomeObject|error response = myHttpClient->/path({[REQUEST_ID_HEADER] : requestId}, myId = myId);
cacheMyResponse(myId, response);

// function to store the response
isolated function cacheMyResponse(string id, SomeObject|error response) returns error? {
    var res = myCache.put(id, response); // can't insert an error type here
    if (res is error) {
        //log
    }
}

Since storing error types are not allowed in the ballerina/cache module, what is the recommended way to store an error response?


Solution

  • The existing API doesn’t allow error type as any does not allow error type. Since we cannot store the error in the cache, one workaround is to store a different record if an error received and reconstruct the error when getting from the cache.