Skip to content

Instantly share code, notes, and snippets.

@dainiusjocas
Created October 26, 2022 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dainiusjocas/4eb6f92290f9c00e90048d6cb248d9a5 to your computer and use it in GitHub Desktop.
Save dainiusjocas/4eb6f92290f9c00e90048d6cb248d9a5 to your computer and use it in GitHub Desktop.
with-err-str
(ns lt.jocas.utils.with-err-str
(:import (java.io PrintStream ByteArrayOutputStream PrintWriter)))
(set! *warn-on-reflection* true)
(defmacro with-err-str
"Evaluates exprs in a context in which *err* is bound to a fresh
PrintWriter. Returns the string created by any nested error printing
calls."
[& body]
`(with-open [baos# (new ByteArrayOutputStream)
ps# (new PrintStream baos#)
pw# (new PrintWriter ps# true)]
(binding [*err* pw#]
~@body
(str baos#))))
(comment
;; example
(with-err-str
(.println *err* "My error"))
;;=> "My error\n")
(comment
;; But in another thread doesn't work
(import '(java.util.concurrent Executor Executors))
(defn print-error-on-thread-pool []
(let [^Executor executor (Executors/newSingleThreadExecutor)]
(.execute executor
^Runnable (fn []
(.println ^PrintWriter *err* "In the thread pool")))
(.shutdown executor)
(.awaitTermination executor 1 TimeUnit/SECONDS)))
(with-err-str (print-error-on-thread-pool))
;;=> ""
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment