
Asp Error in ASP
In Classic ASP, handling errors properly helps you diagnose problems and provide friendly messages to users. ASP provides a simple way to trap runtime errors using On Error Resume Next
and check the Err
object.
Basic Error Handling in ASP
1. Using On Error Resume Next
This tells ASP to continue executing the script even if an error occurs (without stopping).
<%On Error Resume Next ' Enable error handling' Example: Divide by zero causes errorDim x, y, zx = 10y = 0z = x / y ' This causes division by zero errorIf Err.Number <> 0 Then Response.Write "Error Number: " & Err.Number & "<br>" Response.Write "Error Description: " & Err.Description & "<br>" Err.Clear ' Clear error after handlingElse Response.Write "Result: " & zEnd IfOn Error GoTo 0 ' Disable error handling%>
2. Important Err
Object Properties
Property | Description |
---|---|
Err.Number | Error code number (0 if no error) |
Err.Description | Description of the error |
Err.Source | The source of the error (component name) |
Err.HelpFile | Path to help file (if any) |
Err.HelpContext | Help context ID |
3. Custom Error Handling Function Example
<%Sub HandleError() If Err.Number <> 0 Then Response.Write "<b>Error Number:</b> " & Err.Number & "<br>" Response.Write "<b>Description:</b> " & Err.Description & "<br>" ' You can also log errors to a file or database here Err.Clear End IfEnd SubOn Error Resume Next' Example code that may cause errorDim fso, fileSet fso = Server.CreateObject("Scripting.FileSystemObject")Set file = fso.OpenTextFile("C:\nonexistentfile.txt", 1)If Err.Number <> 0 Then HandleError()End IfOn Error GoTo 0%>
4. ASP Built-in Error Object for Global Error Handling
You can create a global error handler in Global.asa file for your site with:
Sub Application_OnError Dim errObj Set errObj = Server.GetLastError() ' Log or display error infoEnd Sub
5. Displaying Friendly Error Pages
Configure IIS to show custom error pages instead of detailed ASP errors for security.
Use
<customErrors>
in IIS or web.config (if using ASP.NET) or IIS error settings.
Summary
Use
On Error Resume Next
to catch runtime errors without crashing.Check the
Err
object for error info.Use
Err.Clear
after handling an error.Consider logging errors for troubleshooting.
Disable error handling with
On Error GoTo 0
when done.
Want me to show you how to log errors to a text file or send error details via email?