Trap errors with pcall()

Introduction

Use pcall() to trap errors by calling a function in protected mode (use to prevent a channel from stopping on “innocent” errors). Demonstrates how to trap an error and call an error handling function, so that code execution can continue.

You can use pcall() to allow your scripts to skip past a message that creates an error, or you can use an error handling function to perform any error handling you choose. When you use pcall the first argument returned to is a boolean that tells you if your function raised an exception. If an error occurred the second argument returned is the error message.

Code to trap errors using pcall() [top]

 -- 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'}) 

 -- example of a function with a table parameter – using the builtin hl7.message{} function
 local Status, MsgOut = pcall(hl7.message, {vmd='demo.vmd', name='ADT'}) 
 
 -- 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

Using the code for pcall() [top]

The code demonstrates how to trap errors using the pcall() function.

How to use the code:

  1. Paste the desired code into any module as required.
  2. Then modify the code to suit your requirements.

More Information [top]