Spring Cache - How can I catch an exception in unless argument?

10,597

Solution 1

You don't have to catch it if exception is thrown in annotated method and propagated further (seems to be your case). In this case there is no key value pair to store in the cache so you get your desired behaviour by default :)

In short: remove "unless" condition and enjoy.

Solution 2

Since the result is a Collection (in this case, a List), you can only use operations attached to that class. So, you can say something like unless="#result != null" or unless="#result.size() > 0"

error is not a valid method in the List class.

Solution 3

Let try with this configuration, it will not cache the data when the exception happen:

@Cacheable(value = "sendAndReceiveMessage", key = "{#requestData.toString()}", unless = "#result instanceof T(java.lang.Exception)")

Share:
10,597
tristobal
Author by

tristobal

Updated on June 15, 2022

Comments

  • tristobal
    tristobal almost 2 years

    I get the following code:

    @Cacheable(value = "cacheName", key = "#someMap.toString()", unless="#result.error")
    public List<Book> methodName(Map<Integer, Integer> someMap) throws BookException {
    //...
    

    The method throws BookException and I want avoid caching the result when this occurs. But when I execute the method:

    org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'error' cannot be found on object of type 'java.util.ArrayList' - maybe not public?
    
  • tristobal
    tristobal almost 6 years
    Ok, suppouse i remove the unless. In case of exception, the @Cacheble will not save into the cache the error? (Thanks by the way).
  • Babajide M. Moibi
    Babajide M. Moibi almost 6 years
    @tristobal It will store a null for the cacheName, you don't want that but rather it should try some other time. Else you'd keep getting null for the same request until the cache values are not longer stored (retention timeout). So if you know your method might return null or throw exceptions, use the unless.
  • tristobal
    tristobal almost 6 years
    So, unless = "#result == null" that's should do the job when a exception is arise?
  • Luan Nguyen
    Luan Nguyen over 5 years
    I have test with @Cacheable, in case the exception happen it will return Exception class so we can not check null or not null here.
  • Luan Nguyen
    Luan Nguyen over 5 years
    unless block will be executed when method finishes. It will have full information of that call: what it the input, what is the result.
  • Luan Nguyen
    Luan Nguyen over 5 years
    for condition, it only the information of input and execute before method run. So it will have no information about the result.
  • Matt
    Matt about 4 years
    @BabajideM.Moibi You are using unless wrong. It should be #result == null || #result.size() == 0. You want to cache unless the result is empty, in which case you don't.