Clojure throws an exception when I don't expect it to

70 views Asked by At

I have this code to get data from sumo logic and other services.

core.clj has this, which parses the arguments and routes it to the right function in route.clj

(def cli-options
  [
    ["-a" "--app APPNAME" "set app. app can be:
                                       sumologic or jira"]
    ["-?" "--help"]
    ])

(defn -main
  [& args]
  (let [{:keys [options summary errors arguments]} (parse-opts args cli-options)]
    (cond
      (:app options) (route/to (:app options) options arguments)
      :else (print_usage summary))))

route.clj has this:

(defn to
  [app options arguments]
  (case app
    "jira" (jira/respond options arguments)
    "sumologic" (sumo/respond)))

And then sumo.clj has this. there are other functions, of course, but showing just the relevant parts.

(defn get-env-var
  [var]
  (let [result (System/getenv var)]
    (if (nil? result)
      (throw (Exception. (str "Environment variable: " var " not set. Aborting")))
      result)))

(def access_key
  (let [user (get-env-var "SUMO_ID")
        pass (get-env-var "SUMO_KEY")]
    [user pass]))

(defn respond
  []
  (let [{:keys [status body error] :as response} (http/get endpoint rest-options)]
    (if error
      (println error)
      (print-response body))))

When I run the program using leiningen as lein run -- -? or even just lein run, I get this error, even though I haven't explicitly called the sumologic function. What am I doing wrong and what are things that I can do differently?

Caused by: java.lang.Exception: Environment variable: SUMO_KEY not set. Aborting
    at clarion.sumo$get_env_var.invoke(sumo.clj:14)
    at clarion.sumo$fn__3765.invoke(sumo.clj:19)
    at clojure.lang.AFn.applyToHelper(AFn.java:152)
    at clojure.lang.AFn.applyTo(AFn.java:144)
    at clojure.lang.Compiler$InvokeExpr.eval(Compiler.java:3553)
1

There are 1 answers

0
Daniel Compton On BEST ANSWER

You have def'd access_key so it is being evaluated when you load the application. You probably want to make it a function instead.