Sunday, August 10, 2008

Error-handling, again.

Here's a better version of my error-handling shell functions. Maybe I am educable, after all.
# common error-handling functions

if [ $_gripe ]; then return 0; else _gripe=1; fi # include guard

warn() { printf "$* at line %s file %s: $msg\n" $(caller) 1>&2 ; }
die() { printf "$* at line %s file %s: $msg\n" $(caller) 1>&2 ; exit -1; }
I have an include guard so I can include it in other shell functions that may be included with one another. I use if, rather than a [test] || alternative construct because I'm often running set -e, and don't want to die because of the test itself.

I have die() printing its own message, instead of calling warn(), so that it reports where it's invoked. Otherwise, warn() announces it's being called by die(). Duh.

It amazes me that after doing this for so long, I can still be fixing bugs in my own code -- and code as basic as this.

No comments: