What is the agent-error method in Clojure?
Overview
Clojure variables are immutable, but with the use of an agent, the storage location can be mutated alongside the use of functions. The changed state of the agent is then returned, as we'll see in the example below.
The agent-error method
The agent-error method is used to throw an error during a failure of an agent in an asynchronous operation.
Syntax
(agent agentname)(agent-error agentname)
Syntax of the agent-error method
Parameters
This method takes one parameter, agentname, which represents the name of the agent.
Return value
This method returns nil when there is no error and an error exception when there is an error with an agent in an asynchronous operation.
Example
(ns clojure.examples.example(:gen-class))(defn func [](def date (agent(java.util.Date.)))(send date + 100)(await-for 50 date)(println (agent-error date)))(func)
Explanation
- Line 3: We define a function,
func. - Line 4: We define a
datevariable with theagentmethod and we set the agent state to ajava.util.Date., which gives us a date. - Line 5: We add
100todate, using thesendagent method, which will throw an error. - Line 6: We set a 50 seconds delay using the
await-formethod to enable the agent to affect the addition. - Line 7: We use
agent-errorto get errors in thedate, which we print using theprintln. - Line 8: We call the function,
func.