Created
October 26, 2022 06:56
-
-
Save dainiusjocas/4eb6f92290f9c00e90048d6cb248d9a5 to your computer and use it in GitHub Desktop.
with-err-str
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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