简体   繁体   中英

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

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?

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.

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.

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)")

Dont throw the exception. Instead use try/catch block and in catch block, assign null value to list. Also use @Cacheable(value = "cacheName", key = "#someMap.toString()", unless="#result==null") . This trick would work for all of the objects including collections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM