Question

How can I avoid getting an error when passing as argument to the function do-http-request an invalid host.
Is there any way that I can catch the error like the Java's exception-handling mechanism ?

Was it helpful?

Solution

Sure, CL has a very nice condition system. One easy option would be wrapping the call to do-http-request in ignore-errors, which returns nil (and the condition as a second value) if an error condition was signalled in the wrapped code. You could then check for nil afterwards.

If you want something more like exception handling in Java, just use handler-case and add an appropriate error clause (I don't have AllegroServe installed, but I suppose you get a socket-error for providing a wrong URL – just change that part if I misread):

(handler-case
    (do-http-request …)
  (socket-error ()
    …))

If you need finally-like functionality, use unwind-protect:

(unwind-protect
     (handler-case
         (do-http-request …)
       (socket-error (condition) ; bind the signalled condition
         …)                      ; code to run when a socket-error was signalled
       (:no-error (value)        ; bind the returned value
         …))                     ; code to run when no condition was signalled
  …)                             ; cleanup code (finally)

You can even get more fancy, and e.g. use handler-bind to handle the condition stack upwards by invoking a restart somewhere down the stack, without unwinding it. For example, if do-http-request provided a restart to try again with another URL, you could handle your error condition by invoking that restart with a new URL to retry. I just mention this for the sake of completeness – it would be overkill for your use case, but being able to resume (possibly expensive) computations easily can be a rather convenient feature.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top