Clojure error - trace error - exception

I have a school assignment that has to be done by next week but here i am sitting and trying to solve a error problem which i really dont get why i am getting this?
According to my teacher i have to get this:
user> (def v (safe (/ 1 0)))
user> v
ArithmeticException java.lang.ArithmeticException: Divide by zero
but what i am getting when doing this is:
java.io.File
user=> (def v (safe (/ 1 0)))
#'user/v
user=> v
#error {
:cause "Divide by zero"
:via
[{:type java.lang.ArithmeticException
:message "Divide by zero"
:at [clojure.lang.Numbers divide "Numbers.java" 158]}]
:trace
[[clojure.lang.Numbers divide "Numbers.java" 158]
[clojure.lang.Numbers divide "Numbers.java" 3808]
[user$fn__17 invoke "NO_SOURCE_FILE" 30]
[clojure.lang.AFn applyToHelper "AFn.java" 152]
[clojure.lang.AFn applyTo "AFn.java" 144]
[clojure.lang.Compiler$InvokeExpr eval "Compiler.java" 3623]
[clojure.lang.Compiler$DefExpr eval "Compiler.java" 439]
[clojure.lang.Compiler eval "Compiler.java" 6787]
[clojure.lang.Compiler eval "Compiler.java" 6745]
[clojure.core$eval invoke "core.clj" 3081]
[clojure.main$repl$read_eval_print__7099$fn__7102 invoke "main.clj" 240]
[clojure.main$repl$read_eval_print__7099 invoke "main.clj" 240]
[clojure.main$repl$fn__7108 invoke "main.clj" 258]
[clojure.main$repl doInvoke "main.clj" 258]
[clojure.lang.RestFn invoke "RestFn.java" 421]
[clojure.main$repl_opt invoke "main.clj" 324]
[clojure.main$main doInvoke "main.clj" 422]
[clojure.lang.RestFn invoke "RestFn.java" 397]
[clojure.lang.Var invoke "Var.java" 375]
[clojure.lang.AFn applyToHelper "AFn.java" 152]
[clojure.lang.Var applyTo "Var.java" 700]
[clojure.main main "main.java" 37]]}

You got it, just the format of the error is a bit different.
If you look at the :via key you'll see the :type key's value is java.lang.ArithmeticException and the :message key's value is Divide by zero
Put them together and you'll get java.lang.ArithmeticException: Divide by zero
This might be an issue with how you're running the REPL. I've never seen errors show up like this but I usually run the REPL with the leiningen command: lein repl

Related

How to implement *load-fn* for :requires in bootstrapped clojurescript

(ns scratch
(:require [cljs.js :as cjs]))
;Let's setup a simple clojurescript string eval that supports namespaces:
(def current-ns 'cljs.user)
(def compiler-state (cjs/empty-state))
(defn eval-text [text]
(println string)
(cjs/eval-str compiler-state text current-ns
{:eval cjs/js-eval
:ns current-ns
:context :expr
:def-emits-var true}
(fn [result]
(set! current-ns (:ns result))
(println result))))
(eval-text "(ns a.a)")
(eval-text "(defn add [a b] (+ a b))")
(eval-text "(add 4 4)")
;I can refer to the function from another namespace explicitly with no problem
(eval-text "(ns x.x)")
(eval-text "(a.a/add 6 6)")
;However when I do
(eval-text "(ns b.b (:require [a.a :refer [add]]))")
On the last line I get:
{:error #error {:message Could not require a.a, :data {:tag :cljs/analysis-error}, :cause #object[Error Error: No *load-fn* set]}}
So I have to create my own https://cljs.github.io/api/cljs.js/#STARload-fnSTAR
and pass it into the :load compiler option to handle this :require even though the compiler state already knows about my namespace as I can call the fully qualified function from another namespace.. Correct?
What is the best way to do that?
Should I create maps that store namespace->source-code from previously evaled code and get namespace->analysis-cache from the compiler state and pass these into the :source and :cache callbacks of my custom load function?
Is there a better / more efficient way to do this?
I believe I found the answer:
The :load option of eval-str can be set to the following function:
(defn load-dep [opts cb]
(cb {:lang :js :source ""})
And it will quite happily resolve. This isn't really apparent from the documentation that the callback can return this value when the namespace/var is already in the compiler state so I'll leave the question here.

Clojurescript namespace as argument

Say I have the following Clojurescript code:
(ns one)
(defn foo [] 1)
(ns two)
(defn foo [] 2)
(ns other)
(defn thing [the-ns] (the-ns/foo))
; now I want to see 1
(other/thing one)
; now I want to see 2
(other/thing two)
How can I achieve this with Clojurescript?
one and two has the same "interface".
PS I know I can pass a function as an argument, but that doesn't answer the question. (e.g. the namespace might have many functions, and I don't want to pass them all)
 Tried ns-resolve
boot.user=> (ns one)
nil
one=> (defn foo [] 1)
#'one/foo
one=> (ns two)
nil
two=> (defn foo [] 2)
#'two/foo
two=> (ns other (:require [cljs.analyzer.api :as api]))
nil
other=> (defn thing [the-ns] (let [f (api/ns-resolve the-ns 'foo)] (f)))
#'other/thing
other=> (other/thing 'one)
java.lang.NullPointerException:
other=> (one/foo)
1
other=> (two/foo)
2
(Yes, there's no trace after java.lang.NullPointerException:, and I go on to show the initial namespaces resolve in the REPL session,)
If I move away from the contrived example, and try this in my Clojurescript project, I get this trace:
#object[Error Error: No protocol method IDeref.-deref defined for type null: ]
Error: No protocol method IDeref.-deref defined for type null:
at Object.cljs$core$missing_protocol [as missing_protocol] (http://0.0.0.0:8000/index.html.out/cljs/core.js:311:9)
at Object.cljs$core$_deref [as _deref] (http://0.0.0.0:8000/index.html.out/cljs/core.js:2164:17)
at cljs$core$deref (http://0.0.0.0:8000/index.html.out/cljs/core.js:4945:18)
at Function.cljs.analyzer.api.ns_resolve.cljs$core$IFn$_invoke$arity$3 (http://0.0.0.0:8000/index.html.out/cljs/analyzer/api.js:346:51)
at cljs$analyzer$api$ns_resolve (http://0.0.0.0:8000/index.html.out/cljs/analyzer/api.js:322:37)
at Function.cljs.analyzer.api.ns_resolve.cljs$core$IFn$_invoke$arity$2 (http://0.0.0.0:8000/index.html.out/cljs/analyzer/api.js:332:37)
at cljs$analyzer$api$ns_resolve (http://0.0.0.0:8000/index.html.out/cljs/analyzer/api.js:318:37)
at eval (eval at <anonymous> (http://0.0.0.0:8000/index.html.out/weasel/repl.js:30:495), <anonymous>:1:108)
at eval (eval at <anonymous> (http://0.0.0.0:8000/index.html.out/weasel/repl.js:30:495), <anonymous>:9:3)
at eval (eval at <anonymous> (http://0.0.0.0:8000/index.html.out/weasel/repl.js:30:495), <anonymous>:14:4)
You can use ns-resolve function to find a var in a namespace.
(ns one)
(defn foo [] 1)
(ns two)
(defn foo [] 2)
(ns other)
(defn thing [the-ns]
(let [f (ns-resolve the-ns 'foo)]
(f)))
(demo.other/thing 'one) ;; returns 1
(demo.other/thing 'two) ;; returns 2
But for this kind of polymorphic behavior, using protocols or multi-methods is more suitable.
UPDATE
The above code works only in Clojure, because ns-resolve does not exists in ClojureScript. In fact, ClojureScript does not have Vars.
But we can manually get the function from namespace object. We also need to mark functions with export metadata flag to prevent function names get "munged":
(ns demo.one)
(defn ^:export foo [] 1)
(ns demo.two)
(defn ^:export foo [] 2)
(ns demo.other)
(defn thing [the-ns]
(let [f (aget the-ns "foo")]
(f)))
(other/thing demo.one)
(other/thing demo.two)

How to 'turn on' cljs.spec

How do I make sure that clojure/cljs.spec is verifying function call arguments and return values?
Say I have this function:
(defn my-inc [x]
(inc x))
After which I have this:
(s/fdef my-inc
:args (s/cat :x number?)
:ret number?)
This code compiles because [cljs.spec.alpha :as s] has been required.
Now I call the function so as to hopefully generate an error:
(my-inc "Not a number")
I would like to see the fdef being used, and see the error message stating that my-inc cannot be called with a string. How do I make this happen in a very general way, for instance with a setting in project.clj or user.cljs?
With this code in user.cljs:
(:require
[cljs.spec.alpha :as s]
[cljs.spec.test.alpha :as ts])
(defn my-inc [x]
(inc x))
(s/fdef my-inc
:args (s/cat :x number?)
:ret number?)
(ts/instrument)
(defn x-1 []
(my-inc "Hi"))
I can call x-1 from the cljs/figwheel REPL, and get this failure message:
#error {:message "Call to #'cljs.user/my-inc did not conform to spec:\nIn: [0] val: \"Hi\" fails at: [:args :x] predicate: number?\n:cljs.spec.alpha/spec #object[cljs.spec.alpha.t_cljs$spec$alpha50572]\n:cljs.spec.alpha/value (\"Hi\")\n:cljs.spec.alpha/args (\"Hi\")\n:cljs.spec.alpha/failure :instrument\n", :data #:cljs.spec.alpha{:problems [{:path [:args :x], :pred cljs.core/number?, :val "Hi", :via [], :in [0]}], :spec #object[cljs.spec.alpha.t_cljs$spec$alpha50572], :value ("Hi"), :args ("Hi"), :failure :instrument}}
I can also get conformance errors when working with a real project running code in a browser. The errors show up in the developer's console on the browser.
Put (ts/instrument) at the bottom of user.cljs to turn instrumentation on for all namespaces for development.
Edit
Just in case you are hit by this problem: https://dev.clojure.org/jira/browse/CLJS-1792
- the fix is to include [org.clojure/test.check "0.10.0-alpha2"] (probably with a more recent version) in your project.clj dependencies.
You can use instrument to check args conformance for certain symbols or all vars.
When called without arguments, instrument wraps all instrumentable vars into a function that checks the args before delegating to the original function.

Get stacktrace as string

I'm using Clojure and I want to get my hands on a stack trace that I can log (ideally, i would like to get it as a String).
I see that (.getStackTrace e) returns a StackTraceElement[] but I don't know how to print something meaningful out of it. My second approach was (.printStackTrace e) with a PrintWriter as a parameter (because I know this is possible in Java), but I don't seem to get the correct syntax.
Thanks.
if number23_cn's solution is a bit much, this is how you can use the result of .getStackTrace as a string (which can then be printed, put in a log, whatever)
(try (/ 1 0)
(catch Throwable t
(map str (.getStackTrace t))))
use clojure.repl.pst get StackTrace, and binding *err* to java.io.StringWriter:
(use '[clojure.repl :only (pst)])
(defmacro with-err-str
"Evaluates exprs in a context in which *err* is bound to a fresh
StringWriter. Returns the string created by any nested printing
calls."
[& body]
`(let [s# (new java.io.StringWriter)]
(binding [*err* s#]
~#body
(str s#))))
(try
(/ 1 0)
(catch Exception e
(let [s (with-err-str (pst e 36))]
(println "Error log:")
(println s))))
Here's a slight improvement over noisesmith's answer. It doesn't leave a lazy seq and has a beautification feature:
(apply str (interpose "\n" (.getStackTrace t)))
You can just use the very useful pr-str function from clojure.core:
(catch Exception e
(l/error "Ho no, an exception:" (pr-str e)))
#error {
:cause nil
:via
[{:type java.lang.NullPointerException
:message nil
:at [my_app$fn__47429$fn__47430 invoke "my_app.clj" 30]}]
:trace
[[my_app$fn__47429$fn__47430 invoke "my_app.clj" 30]
[my_app$my_func invokeStatic "my_app.clj" 13]
[my_app$my_func invoke "my_app.clj" 10]
[my_app$other_func$fn__29431 invoke "my_app.clj" 19]
[my_app$other_func_BANG_ invokeStatic "my_app.clj" 28]
[my_app$other_func_BANG_ invoke "my_app.clj" 27]
[my_app$yet_another_func invokeStatic "my_app.clj" 40]
[my_app$yet_another_func invoke "my_app.clj" 37]
[clojure.core$fn__8072$fn__8074 invoke "core.clj" 6760]
[clojure.core.protocols$iter_reduce invokeStatic "protocols.clj" 49]
[clojure.core.protocols$fn__7839 invokeStatic "protocols.clj" 75]
[clojure.core.protocols$fn__7839 invoke "protocols.clj" 75]
[clojure.core.protocols$fn__7781$G__7776__7794 invoke "protocols.clj" 13]
[clojure.core$reduce invokeStatic "core.clj" 6748]
[clojure.core$fn__8072 invokeStatic "core.clj" 6750]
[clojure.core$fn__8072 invoke "core.clj" 6750]
[clojure.core.protocols$fn__7860$G__7855__7869 invoke "protocols.clj" 175]
[clojure.core$reduce_kv invokeStatic "core.clj" 6776]
[clojure.core$reduce_kv invoke "core.clj" 6767]
[my_app$yet_another_func invokeStatic "data_streamer.clj" 48]
[my_app$yet_another_func invoke "data_streamer.clj" 47]
[my_app$other_func invokeStatic "data_streamer.clj" 66]
[my_app$other_func invoke "data_streamer.clj" 58]
[my_app$other_func$fn__48385 invoke "my_app.clj" 73]
[clojure.core.async$thread_call$fn__6553 invoke "async.clj" 442]
[clojure.lang.AFn run "AFn.java" 22]
[java.util.concurrent.ThreadPoolExecutor runWorker "ThreadPoolExecutor.java" 1135]
[java.util.concurrent.ThreadPoolExecutor$Worker run "ThreadPoolExecutor.java" 635]
[java.lang.Thread run "Thread.java" 844]]}
There is also clojure.stacktrace which has print-stack-trace, print-trace-element and some other helpful functions.
you can use with-out-str
(try
(name nil)
(catch Exception e
(with-out-str (println e))))

clojure - eval code in different namespace

I'm coding something like REPL Server. Request from users evaluates in such function:
(defn execute [request]
(str (try
(eval (read-string request))
(catch Exception e (.getLocalizedMessage e)))))
Each client in separate thread. But they have the same namespace. How can I run code in dynamic created namespace ? So when new client connected, I want to create new namespace and to run client handling loop code there. Or maybe it's possible to run (eval ..) in other namespace ?
Thanks.
upd.
Solved!
Execute function:
(defn execute
"evaluates s-forms"
([request] (execute request *ns*))
([request user-ns]
(str
(try
(binding [*ns* user-ns] (eval (read-string request)))
(catch Exception e (.getLocalizedMessage e))))))
Each client gets it's own namespace by:
(defn generate-ns
"generates ns for client connection"
[] (let [user-ns (create-ns (symbol (str "client-" (Math/abs (.nextInt random)))))]
(execute (str "(clojure.core/refer 'clojure.core)") user-ns)
user-ns))`
(defn delete-ns
"deletes ns after client disconnected"
[user-ns] (remove-ns (symbol (ns-name user-ns))))
offtop: How to make offsets in code snippets on begin of line ?
Solved:
(binding [*ns* user-ns] (eval (read-string request)))
(symbol (str "client-" (Math/abs (.nextInt random)))
I just wanted to add, that this could be achieved with
(gensym "client-")
(I wanted to comment, but it turns our that I can't :))
Changing namespace means that you will have to reinitialize all the aliases, or refer to even clojure.core stuff with a fully qualified name:
user=> (defn alien-eval [ns str]
(let [cur *ns*]
(try ; needed to prevent failures in the eval code from skipping ns rollback
(in-ns ns)
(eval (read-string str))
(finally
(in-ns (ns-name cur))
(remove-ns ns))))) ; cleanup, skip if you reuse the alien ns
#'user/alien-eval
user=> (alien-eval 'alien "(clojure.core/println clojure.core/*ns*)") ; note the FQN
#<Namespace alien> ; the effect of println
nil ; the return value of alien-eval
You can write a macro that mimics
(defmacro my-eval [s] `~(read-string s))
It works better that eval because the symbol resolution of s occurs in the context that calls my-eval. Thanks to #Matthias Benkard for the clarifications.