I was playing around a bit with capturing and displaying the result of evaluating an Arc expression. While there are lots of things an expression could do (writing to a file, calling an web API...) the three results I was looking at were: 1. the return value of the expression 2. or, if it threw an error, the error message 3. any output printed by the expression This resulted in a small function that would call a function you passed it and return the above three as a three element list. This is one of those things that if you need the functionality, it's nice if someone has already packaged it up for you... while, of course, if you don't need it for something, you won't care less :) Thus I thought I might post it in case someone else found it useful. ; calls f with no arguments, and returns a two element list:
; - the return value
; - any output generated during the call to f
(def capture-output (f)
(withs (r nil
output (tostring (= r (f))))
(list r output)))
; calls f with no arguments, and returns a two element list:
; - the return value, or nil on error
; - string error message, or nil if no error
(def capture-error (f)
(on-err (fn (c) (list nil (details c)))
(fn () (list (f) nil))))
; calls f with no arguments, and returns a three element list:
; - return value, or nil on error
; - string error message, or nil if no error
; - any output generated during the call to f
(def capture-output-and-error (f)
(let ((value error) output)
(capture-output (fn () (capture-error f)))
(list value error output)))
(I release this code to the public domain). |