Z1maV1

ExceptionsTools

May 6th, 2024
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. exception = { __tostring = function(e) return "ERROR: " .. e.msg end }
  2.  
  3. function exception:new(msg)
  4. local error_table = {msg = msg}
  5. setmetatable(error_table, self)
  6. self.__index = self
  7. return error_table
  8. end
  9.  
  10. function exception:newObj(error_table)
  11. setmetatable(error_table, self)
  12. self.__index = self
  13. return error_table
  14. end
  15.  
  16. function try(f, catch)
  17. -- execute 'try' statement
  18. local status, exception = pcall(f)
  19.  
  20. -- if an error occurred, execute 'catch' statement
  21. if not status then
  22. catch(exception)
  23. end
  24. end
  25.  
  26. function coroutine_try(f, catch)
  27.  
  28. -- execute 'try' statement but for coroutine
  29. local status, exception = copcall(f)
  30.  
  31. -- if an error occurred, execute 'catch' statement
  32. if not status then
  33. catch(exception)
  34. end
  35. end
  36.  
  37. function print_err(exception)
  38. -- save old color formatting
  39. local bg = term.getBackgroundColor()
  40. local fg = term.getTextColor()
  41.  
  42. -- set colors
  43. term.setBackgroundColor(colors.gray)
  44. term.setTextColor(colors.red)
  45.  
  46. -- print error
  47. print(exception)
  48.  
  49. -- restore colors
  50. term.setBackgroundColor(bg)
  51. term.setTextColor(fg)
  52. end
  53.  
  54. function print_wrn(exception)
  55. --save old color formatting
  56. local bg = term.getBackgroundColor()
  57. local fg = term.getTextColor()
  58.  
  59. -- set colors
  60. term.setBackgroundColor(colors.gray)
  61. term.setTextColor(colors.yellow)
  62.  
  63. -- print error
  64. print(exception)
  65.  
  66. -- restore colors
  67. term.setBackgroundColor(bg)
  68. term.setTextColor(fg)
  69. end
  70.  
  71. return {
  72. exception = exception,
  73. coroutine_try = coroutine_try,
  74. try = try,
  75. print_err = print_err,
  76. print_wrn = print_wrn
  77. }
Advertisement
Add Comment
Please, Sign In to add comment