开发者

Add callback command on any tcl error in tcl script?

开发者 https://www.devze.com 2023-03-08 01:40 出处:网络
Is is possible to specify user defined command on error in tcl s开发者_如何学运维cript? I want to cleanup the memory on if any error comes. I know that last error is saved in errorInfo variable.It\'s

Is is possible to specify user defined command on error in tcl s开发者_如何学运维cript? I want to cleanup the memory on if any error comes. I know that last error is saved in errorInfo variable.


It's not quite clear what really do you want.

You can trap any error using the catch command. If you need it to work on the top level, you can evaluate the rest of your script under catch, like in

catch {
  source ./the_rest_of_the_code.tcl
} err

For asynchronous programs (those using event loop, Tk included) it's not that easy as unexpected errors can be raised in callbacks. To deal with those look at the bgerror command.


The other alternative is to use an execution trace in leavestep mode, which lets you test whether each command executed failed and determine what to do if it occurs. (This is a lot like what you can do with certain types of aspects in AOP.)

proc doIt {} {
    namespace eval :: {
        # Your real code goes in here
    }
}
trace add execution doIt leavestep {::apply {{cmd cmdArgs code result op} {
    if {$code == 1} {#0 == ok, 1 == error
        puts "ERROR >>$result<< from $cmdArgs"
    }
}}}
doIt

It's pretty slow though.


You can also define a bgerror procedure and call your code as a background task:

proc bgerror { msg } {
  puts "bgerror:$msg"
  # Cleanup code here
}

proc troubleCode { } { 
  adjsad s ahda 
}

after 1 troubleCode
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号