Error handling [examples]

List program stack 
DISPLAY CALLS
display calls

https://www.lianja.com/doc/index.php/DISPLAY_CALLS


List program stack 
LIST CALLS
list calls

https://www.lianja.com/doc/index.php/LIST_CALLS


Structure to handle errors and exceptions within a block of code
TRY…CATCH
try
    use example exclusive
catch
    messageBox("Unable to open example table")
endtry
 
//Another example
try
    use example exclusive
catch to oExc
    if oExc.message = "ALIAS name already in use"
        select example
        exit
    else
        messageBox("Unable to open example table")
    endif
endtry
 
//Another example
try
    ? [Outer Try]
    try 
        use example exclusive
    catch to oExc 
        oExc.UserValue = "Nested CATCH message: Unable to handle"
        ?[: Nested Catch]  
        ?[  Inner Exception Object: ]
        ?[  Error: ] + str(oExc.ErrorNo) 
        ?[  LineNo: ] + str(oExc.LineNo) 
        ?[  Message: ] + oExc.Message 
        ?[  Procedure: ] + oExc.Procedure 
        ?[  StackLevel: ] + str(oExc.StackLevel) 
        ?[  LineContents: ] + oExc.LineContents
        ?[  UserValue: ] + oExc.UserValue 
        throw oExc 
    finally
        ?[: Nested FINALLY executed ] 
    endtry   
catch to oExc1
    ?[: Outer CATCH ]
    ?[  Outer Exception Object: ] 
    ?[  Error: ] + str(oExc1.ErrorNo)
    ?[  LineNo: ] + str(oExc1.LineNo) 
    ?[  Message: ] + oExc1.Message 
    ?[  Procedure: ] + oExc1.Procedure 
    ?[  StackLevel: ] + str(oExc1.StackLevel) 
    ?[  LineContents: ] + oExc1.LineContents 
    ?[  ->UserValue becomes inner exception THROWn from nested TRY/CATCH ]
    if oExc1.UserValue.Message = "ALIAS name already in use"
        select example
    endif    
finally
?[: FINALLY executed ] 
endtry
try {
   throw 'myException'; // generates an exception
}
catch (e) {
   // statements to handle any exceptions
   logMyErrors(e); // pass exception object to error handler
}

Start error-handling block
BEGIN SEQUENCE
error = .F.
begin sequence
 
do while not eof()
    if empty(name)
        rec = recno()
        error = .T.
        break
    else
        display name
    endif
    skip
enddo
 
end sequence
 
if error
    set message to "Error: No name in record; &rec."
else
    set message to "End of file reached."
endif

https://www.lianja.com/doc/index.php/BEGIN_SEQUENCE


Number of the last error encountered during a compile operation
CERROR
procedure comp_err
  on error
  if cerror() > 0
      dialog box "Compile Error#" +;
      str(cerror() ,4)
  endif
return
 
on error do com_err
compile proclib.prg

https://www.lianja.com/doc/index.php/CERROR()


Return Operating System dependent error number
DOSERROR
if doserror() > 0
    err = doserror()
endif

https://www.lianja.com/doc/index.php/DOSERROR()


Return Operating System dependent error number
ERRNO
if errno()>0
    err = errno()
endif

https://www.lianja.com/doc/index.php/ERRNO()


Last error encountered
ERROR
? error()
         0

https://www.lianja.com/doc/index.php/ERROR()


Return or set an exit value
ERRORLEVEL
oldlevel = errorlevel(10)
quit

https://www.lianja.com/doc/index.php/ERRORLEVEL()


Disable the logging of errors to the debug file
SET ERRORLOGGING
set errorlogging off

https://www.lianja.com/doc/index.php/SET_ERRORLOGGING


Last error encountered message
MESSAGE
msg=message()

https://www.lianja.com/doc/index.php/MESSAGE()


Trap program errors
ON ERROR
procedure badfile
  on error
  messagebox("File does not exist.")
return to master
 
on error do badfile
use patrons

https://www.lianja.com/doc/index.php/ON_ERROR


Save error information to a specified file when an error occurs
SAVE ERROR
procedure errproc
  on error
  lerrflag = .T.
  save error to errlog
endproc
 
// Attempt to open non-existent table
lerrflag = .F.
on error do errproc
use nontable
if not lerrflag
    // Continue processing
else
    messagebox("Error has occurred.  See errlog.mem for details.")
endif

https://www.lianja.com/doc/index.php/SAVE_ERROR


Define the message displayed for rsp script based WebView errors
SET SHOWERROR

<%@ Language=VFP %>
<html>
<body>
<%
	set showerror off
	set showerror to '<h1>Error has occurred!</h1>';
	+'<p>Return to the <a href="http://www.lianja.com">Home</a> page</p>'
	crash
%>
</body>
</html>

https://www.lianja.com/doc/index.php/SET_SHOWERROR


Disable ON ERROR error handling
SET ONERROR
on error dialog box [Error]
? on("error")
dialog box [Error]
 
set onerror off
? on("error")

https://www.lianja.com/doc/index.php/SET_ONERROR


Retry a command after an error was encountered
RETRY
procedure file_open
  if error() =  15 .and. errno() = 11
      dialog message message()+ ".  Retry?"
      if lastkey() = asc("Y")
          retry
      endif
  endif
return
 
on error do file_open
use accounts exclusive
on error

https://www.lianja.com/doc/index.php/RETRY


Description for latest or specified Operating System dependent error number
STRERROR
if errno()>0
    errstr = strerror( errno() )
endif

https://www.lianja.com/doc/index.php/STRERROR()


Check expression for errors
EXPRCHECK
function CheckExpr
parameter querystring
if exprcheck(querystring) > 0
    dialog box "Error in Query String: " + message()
    m_ret = .F.
else
    m_ret = .T.
endif
return m_ret

https://www.lianja.com/doc/index.php/EXPRCHECK()


Display a string with ‘C’ style picture formatting to the current standard error destination
LOGF

doc_logf.prg

// When %s is specified, the corresponding argument is converted to 
// character format (similar to specifying etos()).
// Widths correspond to the default values, e.g. numerics are 10
logf('It is %s, %s to be more precise\n',year(date()),datetime())
logf('The value of pi is %s\n',pi())
logf('They cost %s per %s\n',$99,100)
logf('Logicals can be %s or %s\n',.T.,.F.)
// Formatting sequences can contain a width, which will left pad with spaces 
logf('Right-justify and pad left: %10s this\n','Like')
// Left justify by placing a '-' directly following the '%' character 
logf('Left-justify and pad right: %-10s this\n','Like')
// %d is for numerics
logf('It is %d\n',year(date()))
// %t and %T are for formating datetime data types.
logf('It is %d, %t to be more precise\n',year(date()),datetime())
logf('It is %d, %T to be even more precise\n',year(date()),datetime())
// %f is for floating point numerics
logf('The value of pi is %f\n',pi())
// Decimal places can also be specified for floating point numerics (%f) 
logf('The value of pi to two decimal places is %4.2f\n',pi())
// %y is for formatting currency data types
logf('They cost %y per %d\n',$99,100)
logf('They cost %y per %d\n',$99,1000)
logf('They cost %y per %d\n',$99,10000)
//%l and %L are for formatting logical datatypes.
logf('Logicals can be %l or %l\n',.T.,.F.)
logf('Logicals can also be %L or %L\n',.T.,.F.)

error.log

It is       2009, 11/11/2009 11:41:51 AM to be more precise
The value of pi is  3.1415926
They cost $99.0000 per        100
Logicals can be True or False
Right-justify and pad left:       Like this
Left-justify and pad right: Like       this
It is 2009
It is 2009, 11/11/2009 11:41:51 AM to be more precise
It is 2009, Wednesday November 11 2009 11:41:51 to be even more precise
The value of pi is 3.141593
The value of pi to two decimal places is 3.14
They cost $99.0000 per 100
They cost $99.0000 per 1000
They cost $99.0000 per 10000
Logicals can be True or False
Logicals can also be Yes or No

https://www.lianja.com/doc/index.php/LOGF()


Error message to be displayed when a validation check fails
ALTER TABLE customer;
  ADD COLUMN timeref CHAR(8);
  CHECK validtime(timeref);
  ERROR "Not a valid time string"

https://www.lianja.com/doc/index.php/ERROR_Column_Constraint


Error message to be displayed when a validation check fails
CREATE TABLE purchase_order;
  (POid i PRIMARY KEY, SuppId i, POtotal n(10,2),;
  CHECK callauth();
  ERROR [Not authorized])

https://www.lianja.com/doc/index.php/ERROR_Table_Constraint


 

Advertisements

Error

Q: 
how can we display an error and either halt code execution or exit from that procedure or function after clearing the error? I’m not sure how to handle this in code but is there a way to detect if an error occurred?A:
It very much depends what the error is. ON ERROR is designed so that developers can handle errors in the way appropriate to their application. When an error occurs, the command assigned to ON ERROR – usually a call to a user-defined error handler function – is run and the error handler can check the current status: error number, procedure name, line number, dbf(), eof() etc. Based on this information, the error handler is designed to resolve the situation, logs details (I think Hank mentionedSAVE ERROR somewhere along the line) and/or exit (QUIT) if a resolution is not possible (bearing in mind that other events are still going on). The ON ERROR can be defined in the App init() to be active in Runtime mode (Lianja.Isruntimemode()) or to behave differently depending on whether you are in Runtime mode or not. Its behaviour can be changed by reissuing ON ERROR with a different command and its current setting queried with ON(“ERROR”).
Within a procedure or function, TRY/CATCH may well be appropriate to handle a particular block of code.
Also, don’t forget that the App Inspector can be seen in both Development and Runtime View in the App Builder (switch it on in Dev View) so that you can have the Error tab visible as you test.



If you get any strange behavior like this then SET DEBUG ON and attach the debug.txt file from the debug directory with your ticket. It tells us what line in our code threw the error.



Q:
In Lianja App builder when I click to open ‘Lianja Demo App’ it seems that it tries to open it as indicated by a progress line bar on top bar but it closes the App builder without any error.
A:
If the Lianja demo app crashes on loading it that sounds like you have previously had Python installed on your machine OR you have RoboForm installed that interferes with the GUI events being dispatched by windows.