Friday, August 10, 2012

Common Lisp error handling example

; Error  handling example.

(define-condition some-error (error)
    ((what :initarg :what :initform "something" :reader what))
    (:report (lambda (condition stream)
                        (format stream "Agh! ~@(~A~) error." (what condition))))
    (:documentation "Some-error condition."))

(defun ignore-some-error1 ()
 " Restart function "
 (print "some error 1")
 T)

(defun function-with-error ()
    " Test function which generate an error. Called directly this will start the debugger/repl. "
    (restart-case (error 'some-error :what "test")
          (use-value (value) value) ; first restart function
          (ignore-some-error1 () (ignore-some-error1)))) ; second restart function

(defun higher-function ()
    " This funtion calls a function which contains an error, but invokes the desired restart.
    Other higher-functions could select different restart or none at all, so the behaviour of 
    the function-with-error under error conditions is controlled on the higher-functions level. "
    (handler-bind ((some-error
                  #'(lambda (c)
                      (invoke-restart 'ignore-some-error1))))
                      (function-with-error )))

No comments: