Advertisement
anonymous1184

MyErrorHandler.ahk

Aug 8th, 2023 (edited)
1,474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #Requires AutoHotkey v1.1
  2.  
  3. /*
  4. If for example, in the very first lines of your script, you add an include to the
  5. error handler as follows:
  6.  
  7. #Include <MyErrorHandler>
  8. ; Or
  9. #Include path\to\MyErrorHandler.ahk
  10.  
  11. And the function is written like this:
  12.  
  13. MyErrorHandler(oError) {
  14.     static init := MyErrorHandler(false)
  15.     if (!oError && !IsSet(init)) {
  16.         OnError(A_ThisFunc, 1)
  17.         return true
  18.     }
  19.     ; Rest of the function here
  20. }
  21.  
  22. That will auto-load the function as the error handler and every error will pass
  23. through that function.
  24.  
  25. More than obvious that the function/lib can be named anything, this name is just
  26. me and my severe lack of ideas on how to name stuff.
  27. */
  28.  
  29. main()
  30.  
  31. Exit ; End of auto-execute
  32.  
  33. main() {
  34.     main_abc()
  35.     FileAppend This will never print`n, *
  36. }
  37.  
  38. main_wvx() {
  39.     FileAppend Before 1st exception`n, *
  40.     try {
  41.         throw Exception("Your error message", , "Your error extra details")
  42.     } catch {
  43.         FileAppend Code to handle the thrown error`n, *
  44.     }
  45.     FileAppend After 1st exception`n, *
  46.     throw Exception("Your error message", , "Your error extra details")
  47.     FileAppend This will never print`n, *
  48. }
  49.  
  50. main_stu() {
  51.     main_wvx()
  52. }
  53.  
  54. main_pqr() {
  55.     main_stu()
  56. }
  57.  
  58. main_mno() {
  59.     main_pqr()
  60. }
  61.  
  62. main_jkl() {
  63.     main_mno()
  64. }
  65.  
  66. main_ghi() {
  67.     main_jkl()
  68. }
  69.  
  70. main_def() {
  71.     main_ghi()
  72. }
  73.  
  74. main_abc() {
  75.     main_def()
  76. }
  77.  
  78. MyErrorHandler(oError) {
  79.     message := "Error: " oError.Message "`n`n"
  80.     if (oError.HasKey("Extra") && oError.Extra != "") {
  81.         message .= "    Specifically: " oError.Extra "`n`n"
  82.     }
  83.     message .= "Call stack:`n"
  84.     loop {
  85.         index := (A_Index * -1) - 1
  86.         stack := Exception("", index)
  87.         if (stack.What = index) {
  88.             break
  89.         }
  90.         message .= Format("`n> {}:{} : [{}]", stack.File, stack.Line, stack.What)
  91.     }
  92.     message .= "`n> Auto-execute" ; `message` will have the format of your choosing
  93.     FileAppend % message, *       ; Save to a file instead
  94.     return true                   ; Exit thread, prevent standard Exception thrown
  95. }
  96.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement