Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Catch errors properly
  • Loading branch information
gf3 committed Feb 29, 2012
1 parent 545323a commit c09a582
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions src/cljbin/eval.clj
@@ -1,16 +1,11 @@
(ns cljbin.eval
(:use [clojail.testers :only [secure-tester-without-def]]
[clojail.core :only [sandbox]]
[clojure.repl :only [doc] :rename {doc repl-doc}]
[clojure.stacktrace :only [root-cause]])
(:require [clojure.string :as string :only [replace trim]])
(:import java.io.StringWriter
java.util.concurrent.TimeoutException))

(defn- safe-read [s]
(binding [*read-eval* false]
(read-string s)))

; A gracious thank you to amalloy in #clojure for the following fn
(defn- read-string-safely [s]
(binding [*read-eval* false]
Expand All @@ -26,16 +21,19 @@
(use 'clojure.repl 'clojure.set 'clojure.test)
(require '[clojure.string :as string]))))

(defn run [code-string]
(defn- execute [sb writer expr]
(try
(let [sb (make-sandbox)]
(for [expr (read-string-safely code-string)
:let [writer (StringWriter.)
res (sb expr {#'*out* writer})
output (str writer)]]
(do
(.close writer)
(string/trim (str output res)))))
(sb expr {#'*out* writer})
(catch TimeoutException _ "Execution timed out!")
(catch Exception e (-> e root-cause str))))

(defn run [code-string]
(let [sb (make-sandbox)]
(for [expr (read-string-safely code-string)
:let [writer (StringWriter.)
res (execute sb writer expr)
output (str writer)]]
(do
(.close writer)
(string/trim (str output res))))))

0 comments on commit c09a582

Please sign in to comment.