Is try-catch like error handling possible in ASP Classic? - error-handling

What options are there in ASP Classic for error handling?
For example:
I'm using the Mail.SendMail function but when switching on the testing server it doesn't work, which is normal. I want to test if mailing is possible, if not then continue and/or show a message.
Any ideas?

There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.
Using JScript you'd use the following type of construct:
<script language="jscript" runat="server">
try {
tryStatements
}
catch(exception) {
catchStatements
}
finally {
finallyStatements
}
</script>
In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:
<%
' Turn off error Handling
On Error Resume Next
'Code here that you want to catch errors from
' Error Handler
If Err.Number <> 0 Then
' Error Occurred - Trap it
On Error Goto 0 ' Turn error handling back on for errors in your handling block
' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.
%>

Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.
If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.
If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.
Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.

1) Add On Error Resume Next at top of the page
2) Add following code at bottom of the page
If Err.Number <> 0 Then
Response.Write (Err.Description)
Response.End
End If
On Error GoTo 0

A rather nice way to handle this for missing COM classes:
Dim o:Set o = Nothing
On Error Resume Next
Set o = CreateObject("foo.bar")
On Error Goto 0
If o Is Nothing Then
Response.Write "Oups, foo.bar isn't installed on this server!"
Else
Response.Write "Foo bar found, yay."
End If

the statement On Error Resume Next should be placed on top of what we want to validate.
On Error Resume Next
'Your code logic is here
Then end with statement like:
If Err.Number <> 0 then
'Your error message goes here'
End if

For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.
http://www.15seconds.com/issue/020821.htm
Here is a link to Archive.org's version

Been a while since I was in ASP land, but iirc there's a couple of ways:
try catch finally can be reasonably simulated in VBS (good article here here) and there's an event called class_terminate you can watch and catch exceptions globally in. Then there's the possibility of changing your scripting language...

Some scenarios don't always allow developers to switch scripting language.
My preference is definitely for JavaScript (and I have used it in new projects). However, maintaining older projects is still required and necessary. Unfortunately, these are written in VBScript.
So even though this solution doesn't offer true "try/catch" functionaility, the result is the same, and that's good enough for me to get the job done.

Related

Run-Time Error 6069

Hello guys i have loop which opens for me Inline Shape (xlsx file attached in doc). It works fine but sometimes i get an error:
Run-time error 6069
It informs that i try to open excel application and probably it's not installed (WOW). When i debug it highlights a lane
wddoc.InlineShapes(lShapeCnt).OLEFormat.Activate
I press "Run" and it works normally like there was no error.
But it's frustrating cause i need to interfere and user who will use this tool can't do that.
It may be some timeout issue. You may try to repeat operation for a while:
...
timeout = Now + #00:00:01# 'Try for 1 second max
On Error Resume Next
Do
Err.Clear
wddoc.InlineShapes(lShapeCnt).OLEFormat.Activate
Doevents 'Sometimes you need to allow events to succeed in some methods
Loop While Err.Number=0 Or Now>timeout
If Err.Number <> 0 Then
MsgBox "Coudn't make call..."
Err.Raise Err.Number
End If
On Error GoTo 0 'or whatever error handler you were using
...

VBA Exception Slipping Through Handler

I have inherited a hideous Excel VBA application, written by a guy who apparently didn't like functions and comments. Opening the source code is like staring into an abyss of madness, with 9 levels of hell indentation awaiting to trap the unwary.
First, the setup.
In the process of debugging an intermittent issue, I have identified a particular line in the primary function as its location. Since the exception is not easy for me to fix, I gave this line, and only this line, an error handler that displays a custom message.
' Lots of stuff cut out
On Error GoTo TechReleaseBuildError
lb_Err1 = BuildDirectories(gj_TechBld.mt_TechRlsOutDir)
On Error GoTo 0
' Lots of stuff cut out
Exit Sub
TechReleaseBuildError:
MsgBox "Error building tech release. Pause the synchronization software and try again."
Stop
Resume
End Sub
The Stop and Resume are only there to help debugging, since the normal error messages that pop up don't have an option to debug the error.
Within the BuildDirectories function, I have identified one line that was causing the error that was being kicked up to primary function. I have placed error handlers in this function as well.
' Lots of stuff cut out
Exit Function
TEST:
Stop
Resume
SynchroRetry:
Dim CurrentError As ErrObject
CurrentError = Information.err
SynchroRetryCounter = SynchroRetryCounter + 1
Debug.Print "Synchro Error, retrying #" + SynchroRetryCounter
Stop
If SynchroRetryCounter > 5 Then
Stop
Information.err.Raise CurrentError.Number, CurrentError.Source, CurrentError.Description, CurrentError.HelpFile, CurrentError.HelpContext
Else
Application.Wait Now + #12:00:03 AM#
Resume
End If
End Function
At the very beginning of BuildDirectories I have placed an On Error GoTo TEST statement as a catch-all error handler so I can identify what lines they are coming from, and also used the SynchroRetry handler for the one line that I already know causes an issue, which I immediately reset back to the TEST handler. The SynchroRetry handler just waits for 3 seconds and retries, failing after the 5th retry.
' For some reason, this line (and only this line so far) causes problems when synchronization software is running.
' The error handler waits for a few seconds then tries again a few times.
Dim SynchroRetryCounter As Integer
SynchroRetryCounter = 0
On Error GoTo SynchroRetry
lj_FSO.CopyFile Source:=lt_RPOFilePath & lt_RPOFileName, Destination:=lt_VinRposDir & "\" & lt_RPOFileName, OverWriteFiles:=True ' Trouble line
On Error GoTo TEST
I have verified with Find that these are the only 3 On Error statements in the function (the only ones in the module, even). The top-level function also has no On Errors other than the two shown.
In brief summary, the top-level function has an error handler on only one line, and the function it encloses also has two error handlers inside it, one for one of its known troublesome lines and a general one that should be encompassing the entire function.
The problem is that some error is occurring that is causing my "Error building tech release." message to display, but does not seem to be triggering the TEST or SynchroRetry error handlers. I cannot imagine how this is possible. I'm relatively new to VBA's monstrosity of an error handling model, but I don't believe I did anything wrong. Did I miss some subtlety here? How is an exception able to bypass my handlers and bubble up the stack like this? I do not believe the assignment or passing of the function value could cause the problem, since their just a Boolean and String value. The problem is also intermittent, and only appears when we have file synchronization software active on the directory this program is copying files to.
So a couple hours after I posted this, I managed to figure it out.
The reason that the Debug button wasn't on the error boxes is because in Options the Error Trapping was set to "Break on Unhandled Error". Changing it to "Break in Class Module" brought the button back.
The reason the exceptions were bypassing my error handlers is because they were happening in my SynchroRetry error handler. In particular, I had to change the first few lines from this:
Dim CurrentError As ErrObject
CurrentError = Information.err
SynchroRetryCounter = SynchroRetryCounter + 1
Debug.Print "Synchro Error, retrying #" + SynchroRetryCounter
to this:
Dim CurrentError As New ErrObject
Set CurrentError = Information.err
SynchroRetryCounter = SynchroRetryCounter + 1
Debug.Print "Synchro Error, retrying #" + CStr(SynchroRetryCounter)
Note the additions of New, Set, and CStr.
Problem solved.

How do I tell VBA code to try again on a specific error?

I have some code which occasionally errors (if someone makes a change in the DB whilst I am trying to read as our locking is set to table level rather than row level and I can't change this).
When it errors I hit debug and then hit continue and it continues on its merry way.
Is it possible on this error only to replicate my actions?
On Error Resume next
will skip over the erroring command and continue on, I don't want this, I want to continue with the command that gave the error as it usually works. However if the error is persistent then there could be a wider issue and we should stop.
I am thinking maybe an error trapping routine which then checks the error code and if it's a match it resumes (not Resume Next), if not then alert the user. Does this sound like the right way?
I have knocked this UNTESTED code up as I am not overly in bed with errors and error handling as I usually build my code to not error but in this case it is out of my control.
ErrHandler:
If Err.Number = -2147467259 Then
ErrorCount = ErrorCount + 1 'This is set to 0 at the start of the code
If ErrorCount > 5 Then
MsgBox "5 Rowfetch errors occured, could be a wider issue"
End
End If
Resume
End If
Err.Raise 'I Think this is wrong, how do I raise an error as VBA normally would?
I figured it out:
ErrHandler:
If Err.Number = -2147467259 Then
ErrorCount = ErrorCount + 1
If ErrorCount > 5 Then
MsgBox "5 Rowfetch errors occured, could be a wider issue"
End
End If
MsgBox "Stopped the error: " & ErrorCount 'In for testing to prove the error happened and was avoided
Resume
End If
Err.Raise Err.Number
This was the part I was not getting right:
Err.Raise Err.Number

VB6 How to catch an ADO Command Timeout error and display custom MsgBox

I have looked through all of the VB6 Error Numbers to no avail, and it seems the command object itself takes care of the error messagebox in the background. What I need to know is if their is someway to change the MsgBox for the ADODB.CommandTimeout error itself. My first thoughts were to just catch the error (using error numbers) and then set a MsgBox that way. However, I can't find any documentation on any error numbers handling ADO Events. Any suggestions?
For whatever it's worth, the error code is 0x80040e31. You can Google for "error 80040e31 timeout expired". And, of course, you can check for that error status in your code.
Here is a list of ADO error codes:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms677004%28v=vs.85%29.aspx
Alright, I got smart and used this:
On Error GoTo ERRS
....
ERRS:
MsgBox Err.Number
This gave me the specific error number to catch (in this case: "-2147217871") and from there use a simple If statement to test if the error number = -2147217871 and if it does, display my MsgBox. Works like a charm (well, as much "charm" as VB6 and ADO has, I guess). I am still getting used to the legacy error handling of VB6. Thanks paulsm4 or your assistance!

Stuck with some weird error in VBA

I am doing project in powerpoint 2007 automation. In that i am using macro programming (VBA). I am getting the following error while run the macro.
Err.Number= -2147024809 (80070057)
but my concern is not with error Because i want to catch this error and base on this error i want to perform some action.
Thats why i try to code like this for error handing code:
OnError Goto Err:
'some code
Err:
If Err.number = -2147024809 (80070057) then
'do something
end if
Resume next
So bascially if i write error number in this way then its not allow it. it gives error.
and major thing is when error occurs sometime it did not go to "Err : ". It just pop-up error with "End" and "Debug" options.
While it seems to work, I'd be cautious about using a reserved object name (Err) as a label, for one thing.
On Error GoTo ErrorHandler
' Your code here
' Make sure you don't hit the errorhandler when there's
' no error:
NormalExit:
Exit Sub ' or Function, whichever this is
ErrorHandler:
If err.Number = 123456788 Then
' Take corrective action
' then continue
Resume Next
End If
' Trap other specific or general errors here
' Then make sure you know where you're going to exit:
Resume NormalExit
If you need to trap very specific errors that might occur only at certain places in your code, you can also do a local errorhandler:
On Error Resume Next
' Some code that might cause problems
' Did it throw the error you're trying to trap?
If Err.Number = 12398745 then
' Corrective action
End If
' And now we return to our regularly scheduled error trapping
On Error GoTo ErrorHandler
Error numbers are numeric: -2147024809, its just displayed to you as the string "-2147024809 (80070057)" for clarity (80070057) being the error number in hexadecimal.
You want;
if err.number = -2147024809 then ....
or if you so choose
if err.number = &h80070057 then ....
The 80070057 part of the error message is the unsigned hexadecimal version of the negative number -2147024809. Remove that part of your code and you will be fine, if you want to keep track of the hex version of the number (can be useful for researching errors via Google etc) then just add it as a comment.