Trap function call errors with pcall()

Verified
Added by iNTERFACEWARE

Use pcall() to trap errors by calling a function in protected mode (use to prevent a channel from stopping on "innocent" errors).

Source Code
   -- call a function with no parameters
   local Status, Result = pcall(myfunc)
   
   -- call a function with multiple parameters (just add more as needed)
   local Status, Result = pcall(myfunc,'param 1', 'param 2', 'etc...')
   
   -- call a function with a table parameter
   local Status, Result = pcall(myfunc,{'John', 'William', 'Smith'})
   local Status, Result = pcall(myfunc,{[1] = 'John', [2]='William', [3]='Smith'})
   local Status, Result = pcall(myfunc,{['fname'] = 'John', ['mname']='William', ['lname']='Smith'}) 
   
   -- call a function with a string and table parameters
   local Status, Result = pcall(myfunc,'param 1', {'John', 'William', 'Smith'})

   -- Dummy code process the returned error
   if Status == false then
      if Result == 'I am a FATAL ERROR' then
         -- do some cleanup then stop on FATAL ERROR
         error('Fatal error occurred: '.. Result) 
         else
         -- do some cleanup and continue processing
         end
   end
Description
Use pcall() to trap errors by calling a function in protected mode (use to prevent a channel from stopping on "innocent" errors).
Usage Details

Using pcall() allows you to call a function and catch an error if it occurs. Then you can test the error and decide what to do, e.g., cleanup/recover and continue for non-fatal errors, and cleanup then exit for fatal errors.

How to use the snippet:

  • Copy the desired pcall() example into your script
  • Change the code to call your own function
  • Adapt the dummy error processing code