Question

Trapping VBScript Errors

Asked by: calvinrsmith

how can I trap an Error ex. if a database operation fails instead of having vbscript display an error message I would like to trap the error myself.  In VB I could use On Error this does not seem to work with VBScript

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
1999-10-19 at 16:18:58ID10221734
Tags

vbscript

,

error

Topic

Web Authoring

Participating Experts
3
Points
20
Comments
6

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Error Trapping
    In runtime errors such as err.3200 Delete record on related files can not be trapped but when an .exe is compiled the error trap will work. I have found this with a few other errors. Why does the trap work with a .exe and not while running in VB. I know this happens in ver 5...
  2. Trapping errors
    I am using VBScript on the Server side. I would like to trap the erros (both ADODB errors and the normal programming errors) For the first type of error, I use the ADODB.error object. The problem rises in the second phase. Here I use the On Error Resume Next (of VB). Tha...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: canadian5Posted on 1999-10-20 at 06:53:13ID: 2141877

Try
On Error Resume Next

And for error handling I believe you use

If err <> 0 then
....
end if

On Error Goto doesn't work in VBScript to my knowledge.

 

by: jrubinPosted on 1999-10-20 at 10:01:14ID: 2142525

'turn on error handling
On Error Resume Next

'try to do what you're doing - here I'm trying
'to open a connection to a database
objConn.Open "DSN=whatever;PWD=whatever;UID=whatever;DATABASE=whatever;"

'test for the error
If objConn.Errors.Count > 0 Then
    'do whatever you want
End If            

'turn error checking off
On Error Goto 0

As canadian5 said, you can also check ther Err object rather than the error collection of the object you're working with (I was using the connection object above). Hope that helps.

 

by: suebrown99Posted on 1999-10-21 at 07:10:00ID: 2145644

There is a great discussion of web page error handling at http://msdn.microsoft.com/workshop/c-frame.htm?939160113522#/workshop/author/script/weberrors.asp

I use a technique I found there.  It involves using On Error Resume Next, and then wherever an error might occur, I trap it by checking to see If Err.Number <> 0.  

Inside the trap, I call a subroutine that is included from a separate file.  In this subroutine (called TrapError), I first log all pertinent information to a text file on my server, and then redirect to a page that displays a user-friendly error message, depending on what the error was.  If the error was, say, a SQL timeout error, you could retry the SQL connection automatically instead of redirecting to an error message.

Also, canadian5 was correct in stating that On Error GoTo does not work in VBScript.

 

by: calvinrsmithPosted on 1999-10-21 at 08:39:31ID: 2146057

Your "answer" is nothing more than a "here is where you can do more research" as of yet canadian5 had the best "answer".  jrubin had a different approach that also seems to work.

canadian5 - post as answer and this question is over.

 

by: suebrown99Posted on 1999-10-21 at 10:51:31ID: 2146496

OK, here's more specific code -- I didn't put it all here last time because it's pretty long.  Sorry.  Hope this helps.


Step One:  Opening a connection to a database and Trapping the Error in our .asp file:

   On Error Resume Next      
      
   Set Conn = Server.CreateObject ("ADODB.Connection")
   Conn.Open Session("ConnectionString")
            
    'Check for errors opening the database connection      
    If err.number <> 0 Then                        
        sErrMsg = "[Error opening connection.]"
        trapError server.URLEncode(Request.ServerVariables("URL")), _
              Err.Number, _
              Err.Description, _
              sErrMsg            
    End If

Step 2:  The trapError sub routine (actually kept in a separate file and #included because it's accessed from many .asp files):

Sub trapError(docTitle, errNum, errDesc, msg)

    Dim errMsg
    Dim errLog
    Dim LogFile
    Dim FileSys
    Dim ShowID      
    Dim ErrorLogFullName
    Dim sLine
   
   On Error Resume Next
      
    ErrorLogFullName = "LOG_ERROR.txt"

    Err.Clear

      
Select Case errNum

      ' Call this subroutine with errNum=1 for all SQL timeout errors
     Case 1 ' SQL TIMEOUT
         ErrLog = "Error: " & errdesc
      ' Call this subroutine with errNum=2 when data objects are down
      Case 2 ' MSDATA objects error
          ErrLog = "MSCOM error - data objects are down"
      Case 5 ' Invalid procedure call or argument
      Case 6 ' Overflow
      Case 7 ' Out of memory
      Case 9 ' Subscript out of range
      Case 10 ' This array is fixed or temporarily locked
      Case 11 ' Division by zero
      Case 13 ' Type mismatch
      Case 14 ' Out of string space
      Case 17 ' Can't perform requested operation
      Case 28 ' Out of stack space
      Case 35 ' Sub or Function not defined
      Case 48 ' Error in loading DLL
      Case 51 ' Internal error
      Case 52 ' Bad file name or number
      Case 53 ' File not found
      Case 54 ' Bad file mode
      Case 55 ' File already open
      Case 57 ' Device I/O error
      Case 58 ' File already exists
      Case 61 ' Disk full
      Case 62 ' Input past end of file
      Case 67 ' Too many files
      Case 68 ' Device unavailable
      Case 70 ' Permission denied
      ErrMsg = "You do not have correct permissions to do that"            ErrLog = "I don't care about info on this one"
      Case 71 ' Disk not ready
      Case 74 ' Can't rename with different drive
      Case 75 ' Path/File access error
      Case 76 ' Path not found
      Case 91 ' Object variable not set
      Case 92 ' For loop not initialized
      Case 94 ' Invalid use of Null
      Case 322 ' Can't create necessary temporary file
      Case 424 ' Object required
      Case 429 ' ActiveX component can't create object
      Case 430 ' Class doesn't support Automation
      Case 432 ' File name or class name not found during Automation operation
      Case 438 ' Object doesn't support this property or method
      Case 440 ' Automation error
      Case 445 ' Object doesn't support this action
      Case 446 ' Object doesn't support named arguments
      Case 447 ' Object doesn't support current locale setting
      Case 448 ' Named argument not found
      Case 449 ' Argument not optional
      Case 450 ' Wrong number of arguments or invalid property assignment
      Case 451 ' Object not a collection
      Case 453 ' Specified DLL function not found
      Case 455 ' Code resource lock error
      Case 457 ' This key is already associated with an element of this collection
      Case 458 ' Variable uses an Automation type not supported in VBScript
      Case 500 ' Variable is undefined
      Case 501 ' Illegal assignment
      Case 502 ' Object not safe for scripting
      Case 503 ' Object not safe for initializing
      Case 504 ' Object not safe for creating
      Case 1001 ' Out of memory
      Case 1002 ' Syntax error
      Case 1003 ' Expected ':'
      Case 1005 ' Expected '('
      Case 1006 ' Expected ')'
      Case 1007 ' Expected ']'
      Case 1010 ' Expected identifier
      Case 1011 ' Expected '='
      Case 1012 ' Expected 'If'
      Case 1013 ' Expected 'To'
      Case 1014 ' Expected 'End'
      Case 1015 ' Expected 'Function'
      Case 1016 ' Expected 'Sub'
      Case 1017 ' Expected 'Then'
      Case 1018 ' Expected 'Wend'
      Case 1019 ' Expected 'Loop'
      Case 1020 ' Expected 'Next'
      Case 1021 ' Expected 'Case'
      Case 1022 ' Expected 'Select'
      Case 1023 ' Expected expression
      Case 1024 ' Expected statement
      Case 1025 ' Expected end of statement
      Case 1026 ' Expected integer constant
      Case 1027 ' Expected 'While' or 'Until'
      Case 1028 ' Expected 'While', 'Until' or end of statement
      Case 1030 ' Identifier too long
      Case 1031 ' Invalid number
      Case 1032 ' Invalid character
      Case 1033 ' Unterminated string constant
      Case 1034 ' Unterminated comment
      Case 1037 ' Invalid use of 'Me' keyword
      Case 1038 ' 'loop' without 'do'
      Case 1039 ' Invalid 'exit' statement
      Case 1040 ' Invalid 'for' loop control variable
      Case 1041 ' Name redefined
      Case 1042 ' Must be first statement on the line
      Case 1043 ' Cannot assign to non-ByVal argument
      Case 1044 ' Cannot use parens when calling a Sub
      Case 1045 ' Expected literal constant
      Case 1046 ' Expected 'In'
      Case 4096 ' Microsoft VBScript compilation error
      Case 4097 ' Microsoft VBScript runtime error
      Case -2147217900
      ErrLog = "Incorrect syntax near [SQL ERROR]:" & errdesc
      Case 3704 ' SQL Server not available or timed out      
      ErrLog = "SQL Server not available or timed out [SQL ERROR]:" & _
                    errdesc
      Case Else
End Select

    ' open up access to the logfile
    set FileSys = CreateObject("Scripting.FileSystemObject")
    set LogFile = FileSys.OpenTextFile (ErrorLogFullName, 8, True)

    ' generate a log entry for this error
    If len(errLog) = 0 Then      
    'Use a generic message (errDesc)
         sLine =  (Now & vbTab & msg & vbTab & errNum & vbTab &  _
               errDesc & vbTab & URLDecode(docTitle) & vbTab & _
               Request.ServerVariables("HTTP_USER_AGENT"))
    Else
    'Use a message defined above (errLog)
        sLine = (Now & vbTab & msg & vbTab & errNum & vbTab &  _
                     errLog & vbTab & URLDecode(docTitle) & vbTab & _
         Request.ServerVariables("HTTP_USER_AGENT"))
    End If

    LogFile.writeline sLine
    LogFile.Close
      
    ' display the user's error page
    ' NOTE:  We need an absolute URL here because we don't know which page
    '        (in which directory) is calling this method, so a relative
    '        URL is impossible to construct.
   Response.Redirect Request.ServerVariables("APPL_PHYSICAL_ADDR")  & _
                               "/includes/ShowError.asp?errorNum=" & errNum
                                                
End Sub

Step 3:  Helper function to decode URL

' helper function used to un-encode a URL string
Function URLDecode(strToDecode)
      Dim strIn      
              Dim strOut
      Dim intPos
      Dim strLeft
      Dim strRight
      Dim intLoop
      strIn = strToDecode
      strOut = ""                  'The result string
      intPos = instr(strIn, "+")      'look for + and replace with a space
      Do while intPos
            strLeft = ""
            strRight = ""
            If intPos > 1 Then strLeft = Left(strIn, intPos -1)
            If intPos < Len(strIn) Then strRight = Mid(strIn, intPos +1)
            strIn = strLeft & " " & strRight
            intPos = Instr(strIn, "+") ' and then look for next one
            intLoop = intLoop + 1
      Loop
      intPos = Instr(strIn, "%")      'Look for ASCII coded chars
      Do While intPos
            If intPos > 1 Then strOut = strOut & Left(strIn, intPos -1)
            strOut = strOut & Chr(Cint("&H" & Mid(strIn, intPos + 1, 2)))
            If intPos > (Len(strIn) - 3) Then
                  strIn = ""
            Else
                  strIn = Mid(strIn, intPos + 3)
            End If
            intPos = Instr(strIn, "%")      'and then look for next one
      Loop
      URLDecode = strOut & strIn
End Function

Step 3:  The ShowError.asp file:

    Dim ErrorType
    Dim ErrMessage

    ErrorType = clng(Request.QueryString("errorNum"))

    '----- Build Error Message to display based on the type of error -----'
    Select Case ErrorType
        Case SQL_OTHER
      ErrMessage = "We are sorry, but we are experiencing an " & _
                    "unusually high volume of traffic."
        Case else
      ErrMessage = "We are sorry, but we are experiencing " & _
                    "temporary problems with our web site."
    End Select

    <HTML>
        <HEAD></HEAD>
        <BODY>
            <% =ErrMessage %>
        </BODY>
    </HTML>

 

by: canadian5Posted on 1999-10-21 at 11:14:01ID: 2146569

Here you go,  read my comment above for the answer...

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...