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 date variable with the agent method and we set the agent state to a java.util.Date., which gives us a date.
  • Line 5: We add 100 to date, using the send agent method, which will throw an error.
  • Line 6: We set a 50 seconds delay using the await-for method to enable the agent to affect the addition.
  • Line 7: We use agent-error to get errors in the date, which we print using the println.
  • Line 8: We call the function, func.