Error
The basic skills required to use ASP are described earlier, and the other issue in this chapter is what to do when an ASP error occurs, and what happens when an ASP goes wrong. When a carefully choreographed ASP page problem stops executing, the user generally gets only a few useful suggestions, such as clicking the Refresh button, or contacting the Web administrator of the site to tell them that your page is not working properly, and so on.
In addition to providing useful information, this chapter wants to provide a help area. We will describe in detail how errors occur in scripts and pages, the types of errors that can occur, and what causes these errors. What is more important is to discuss how to avoid mistakes as much as possible, and how to deal with them if they cannot be avoided.
Therefore, this chapter will explore the page debugging technology, that is, how to spend a little energy and time to find errors and solve problems.
This chapter includes the following elements:
· The type of error that can occur.
· How to prevent the emergence of various errors.
· How to handle these errors properly if you cannot prevent errors from occurring.
· How to discover and handle scripting errors and other types of errors.
· How to use the custom error page to get the error message.
· How to record errors to monitor our site.
· Create a custom error page and an error log file.
· Provide related online help.
This chapter does not address the various special types of errors that occur when you access a data source using ActiveX Data Objects (ADO). Like many components, ADO provides its own error-handling system, which is discussed in depth in chapter 8th. This chapter starts by discussing the various types of errors that can occur, enabling us to recognize these errors and take appropriate action.
It is said that in the depths of Africa's darkest rainforest, there are such a group of programmers whose code of procedure has never been wrong. Unfortunately, they have never had the pleasure of debugging an application that doesn't work properly. Debugger code is a really fun job, so we have to face this problem, in the process of debugging procedures to test our observation and lateral thinking ability. Most "real world" programmers can experience these pleasures as a good thing.
Of course, some people will say that the debugger is more of a chance than a judgment. It takes a lot of time to debug a faulty program, which in a way can be said to depend on luck. However, if the first step starts at the right place, you may be able to solve the problem more quickly.
But this is not the way the program should be debugged. Theoretically, when a program fails, the error should be tracked in a logical or sequential manner. As a smart and experienced programmer, this is the common method of debugging, only amateurs can change the value of the variable in the program, everywhere add Response.Write statements for debugging.
However, in order to be able to logically track bugs in a program, you must understand the basics of how the error occurred, and more importantly, know where the error occurred so that you can quickly find the appropriate place. This chapter discusses the different kinds of errors that can occur in a program, the different manifestations of errors, and how to record and troubleshoot these errors. It is also important to explain how to avoid these errors.
This chapter starts by describing the different kinds of errors that may occur, and if you think your code doesn't make any mistakes, skip to the next chapter.
7.1 Kinds of Errors
7.1.1 syntax or "compile" error
When we first run the newly written program code, the first type of error that we usually see is "syntax error." This is what is said, the syntax error on the program code. It's like using the wrong grammar in writing so that the reader doesn't know what it means. Interpreters, such as the scripting engine, and compilers require more rigorous and accurate syntax.
Grammatical errors are often the first to appear and need to be excluded. In most cases, the interpreter and the compiler indicate the line number and the character position in the row, and what is missing at the appropriate location. Here's a simple example, as shown in the following procedure:
<%
Response.Write "The repayments for your loan are $" & chrpayment _
& ' per ' & Strinterval &, due on the ' &strday & ' of each '
& Strinterval & "."
%>
We hope to get the following results:
The repayments for your loan are $124.50/month, due on the 12th of each month.
The results are actually as shown in Figure 7-1:
Bean-Bean Note:
If your error message does not appear "grammatical error", please change your winnthelpiishelpcommon500-100.asp as follows (plus two lines of bold):
...
Dim bakcodepage
Bakcodepage = Session.CodePage
Session.CodePage = 936
Response.Write Server.HTMLEncode (Objasperror.category)
If objasperror.aspcode > "" Then Response.Write Server.HTMLEncode ("," & objASPError.ASPCode)
Response.Write Server.HTMLEncode ("0x" & Hex (Objasperror.number) & ")" & "<br>"
If objasperror.aspdescription > "" Then Response.Write Server.HTMLEncode (objasperror.aspdescription) & "<br > "
blnErrorWritten = False
Response.Write "<B>"
If objasperror.description > "" Then Response.Write Server.HTMLEncode (objasperror.description) & "<br>"
' Show the ' Source if it's available and the ' request is ' same machine as IIS
...
The 3rd line in the file is the 2nd line of the Response.Write statement. When you report an error message, the VBScript interpreter ignores the boot spaces and tabs in a row. So after you've finished counting 26 characters, you can find where the syntax is wrong, where a double quote is clearly missing. With double quotes and then run this page, we can get as shown in Figure 7-2:
This is another simple mistake. The error actually occurs on line 3rd instead of line 4th. We missed the continuation line ' _ ' at the end of the third line. The program code should be:
<%
Response.Write "The repayments for your loan are $" & chrpayment _
& ' per ' & Strinterval & ', due on the ' &strday & ' of each ' _
& Strinterval & "."
%>
1. Where did the mistake come from?
Note that the script interpreter only points out where the error was found, but it is not necessarily where the error actually appears. In the example above, the syntax for the first three lines is correct and produces the corresponding output, which is precisely the 4th row that causes the problem because the line begins with an illegal character, and the script interpreter does not realize that the line is part of the previous line.
Such errors are common because we typically consider the text content to be output rather than the correct order of double quotes, hyphens ("&" in VBScript), continuation lines, and so on.
Syntax errors caused by a keyword, intrinsic function name spelling error, or an illegal argument list for a function are usually easier to find because the error message hint may indicate the actual location of the error. For example: The following code is to write tomorrow's date to the page.
Response.Write DateAdd (Now (), "D", 1)
The actual results are shown in Figure 7-3:
This is because the syntax of the DATEADD function should be:
DATEADD (interval_string, Interval_number, start_date)
So the code should be rewritten as follows:
Response.Write DateAdd ("D", 1, Now ())
The script interpreter has detected that we provide a character data for the second parameter, and the DateAdd function requires an integer data type.
Code structure and script structure
Another reason for syntax errors is that you use nested or complex script structures when making Web pages, such as if Then ... Else ... End If or do while ... Loop. This can sometimes result in difficult to find grammatical errors.
For example, the following procedure:
<%
If Len (Request.Form ("Cmdset")) Then
Strcountername = Request.Form ("Lstset")
Strnewvalue = Request.Form ("Txtset")
If IsNumeric (Strnewvalue) Then
Intnewvalue = Cint (strnewvalue)
Objcounters.set Strcountername, Intnewvalue
Response.Write "Set Counter" & Strcountername & "to" & Strnewvalue
Else
Response.Write Strnewvalue & "is not a valid number"
If Len (Request.Form ("Cmdremove")) Then
Strcountername = Request.Form ("Lstremove")
Objcounters.remove Strcountername
Response.Write "Removed counter" & Strcountername
End If
End If
%>
The resulting error is shown in Figure 7-4:
Why do I need an end statement in a Web page program? If you look at the program, you can see that you have lost an end if, not an end, and there should be another ending if at the bottom of the program.
...
Response.Write "Removed counter" & Strcountername
End If
End If
End If
%>
In this case, you can easily find the appropriate error based on the indentation format of your code. Especially when the error message indicates the approximate position of the error, the error location can be found soon. However, this code is very short, and if there are 40 additional lines of code in the delimiter <%...%>, the error line number may still point to the last line 56, and if the other script structure in the new code messes up the nested structure, the error may point to another location.
2. About JScript
If you're not a JavaScript whiz and really want to experiment with some syntax errors, switch from VBScript to JScript. JScript is more demanding than VBScript to write a program, and is sensitive to keyword and variable name case, see the following section of the program.
<%
var dattoday = new Date ();
Response.Write (Dattoday.getmonth ());
%>
Running this program results in an "object doesn ' t support this or method" (the object does not support such a property or methods) error, as shown in Figure 7-5:
The reason is simple, the JScript function that returns the number of months is getmonth, not getmonth. The following procedure will work correctly.
<%
var dattoday = new Date ();
Response.Write (Dattoday.getmonth ());
%>
Of course, if you retry this program, you may not get the same error message. The first time we ran this program, we got the error shown in Figure 7-6.
What's wrong with line 2nd? If you use the JScript interpreter, no errors appear. Error message description, this is a VBScript syntax error. Using the VBScript interpreter to parse a JScript program, you get strange error messages.
Remember that languages are being used
This is why this error occurs because you forgot to add the @language directive before the page's code. The default is VBScript (if it is not changed in the registry or in Internet Services Manager), so the VBScript engine is used to process programs that are not preceded by @language directives. Always using the @language directive is a good way to avoid this error, even if you have been using the default language that is set exclusively for your own server. This way, if you move the Web page to a different server in another default language, you get the expected results.
The content described here is unlikely to cover all possible grammatical errors, as people dwell on the reasons for the error, and the error message is not always as accurate as one might expect. The ideal approach would be for the ASP to provide us with a concise error display page with a full and accurate description of the error, even asking if we want to automatically handle the error. The fact that the application Microsoft Script Debugger is trying to provide us with similar functionality is discussed later in this chapter and outlines some of the key points to avoid grammatical errors. Now we continue to look at the second category of errors that often occur in Web pages.
7.1.2 semantics or "Run Time" error
The discovery and handling of grammatical errors is annoying, but in programming there are some really "exciting" other types of errors-semantic errors (semantic error) or "Run-time" errors (runtime error). This type of error is only found when you run a script code or other program. In other words, the complete and valid code has been interpreted or compiled by an interpreter or compiler, resulting in an error in execution. The term "Run-time error" means the result of a semantic error, meaning that such errors exist in the semantics of the code, and they become visible when the code is run.
This distinction stems from the fact that the program compiler or interpreter must establish a description of the internal code before processing the program code, involving a plurality of structure start and end matches to indicate what each structure contains, and then analyze each sentence to know how to execute the sentence. For example, if you have an if Then in your program code ... Else ... End IF structure, the first step of the interpreter or compiler is to analyze which statements are in the "Then" section and which are in the "Else" section. The goal of this step is to determine which branch to execute after testing the IF condition in the structure.
The real difference between compilers (such as those seen in programming languages like Visual Basic and C + +) and interpreters (such as those used for scripting languages like VBScript and JScript) is that the compiler does not attempt to run program code, but after two preprocessing of the source program, form a binary instruction or symbol code, and form an. exe file or a. dll file. The interpreter does not contain code files, but is executed gradually at run time.
1. Error that causes the run to stop
If your program contains a semantic error, you usually get a hint at runtime. If you're lucky, the program stops when the error occurs, which makes it easy to find out where the error is. For example, the following program defines an array of six elements.
<%
Dim arrvalues (5) ' to hold six elements, indexed from 0 to 5
Arrvalues (6) = "Whoops, got an error"
%>
If you attempt to read or set the element value labeled 6, you can get a run-time error, as shown in Figure 7-7:
Note that the error type here is "runtime" (equivalent to semantic) errors, not grammatical errors. The error message shows the number of rows in the error and the description of the error, which helps us find the corresponding error more easily. But this is a simple example, and in more complex program code, this error can occur in a program that traverses some values and adds them to an array. As shown below:
<%
Dim arrvalues (5) ' to hold six elements
For intloop = 0 to Intlistcount ' The number of items in some list
Arrvalues (intloop) = Request.Form ("SelectedItems") (Intlistcount)
Next
%>
In this case, it is possible to get too many list entries, or the index of the array is not enough, according to the requirements of the code can be judged that the error, and can increase the size of the array to resolve this error.
<%
Dim arrvalues (a) ' to hold eleven elements
For intloop = 0 to Intlistcount ' The number of items int some list
Arrvalues (intloop) = Request.Form ("SelectedItems") (Intlistcount)
Next
%>
or set the parameters of the loop accordingly to resolve this error.
<%
Dim arrvalues (5) ' to hold six elements
Intarraymax = Intlistcount
If Intarraymax > 5 Then intarraymax = 5
For intloop = 0 to Intarraymax ' only add the ' I six items
Arrvalues (intloop) = Request.Form ("SelectedItems") (Intlistcount)
Next
%>
Many other run-time errors can cause Web page runs to stop, such as the instantiation of some components or objects that failed because of a ProgID error or because the component was not installed properly. In these cases, the result always gives an "ActiveX cannot Create Object" error message, followed by the line number of the Server.CreateObject method called.
2. Error generating Error results
As mentioned above, we may be lucky if we encounter a run-time error that stops the program code. But the other scenario is that the program performs well, as if nothing had happened, resulting in a false result. This is the most difficult to find and solve the error, because there is no awareness of what went wrong. For example, suppose you have a Web page that takes a user's birthday as a date value and displays the date elements separately (you can add them as three entries to a database).
<%
' Get the ' value from the Request and display it
Datbirthdate = Request.Form ("Birthdate")
Response.Write "The value you entered are:" & datbirthdate & "<P>"
' Get the individual date elements
Intday = Day (datbirthdate)
Intmonth = Month (datbirthdate)
Intyear = year (datbirthdate)
' and display them
Response.Write "Day:" & Cstr (Intday) & "<BR>"
Response.Write "Month:" & Cstr (intmonth) & "<BR>"
Response.Write "Year:" & Cstr (intyear) & "<BR>"
%>
Figure 7-8 is the result, which is displayed with the American date style month/day/year, as if everything is fine.
However, if you enter an illegal date, or leave the Input text box blank, you get a run-time error, as shown in Figure 7-9:
(1) If not a JScript expert
This is not a big problem when looking for errors, because we can quickly find out why there are errors. The fact that the Web stops running helps us track the error. However, unexpected errors may occur. For example, to rewrite the program code with JScript, because it is not a JScript expert, there are some minor errors.
<%
Get the value from the Request and display it
var datbirthdate = new Date (Request.Form ("birthdate"));
Response.Write ("The value you entered are:" + datbirthdate + "<P>");
Get the individual date elements
Intday = Datbirthdate.getday ();
Intmonth = Datbirthdate.getmonth ();
Intyear = Datbirthdate.getyear ();
and display them
Response.Write ("Day:" + intday.tostring () + "<BR>");
Response.Write ("Month:" + intmonth.tostring () + "<BR>");
Response.Write ("Year:" + intyear.tostring () + "<BR>");
%>
Figure 7-10 is the result of the run, although the program does not stop running and give a run-time error, or immediately see some of these problems, the month can not be 0.
The problem arises because the getmonth function of JScript Returns the result of the 0~11 range, so you need to add another 1 to get the correct result.
Intmonth = Datbirthdate.getmonth () + 1;
(2) Derivative error
Even if you do not assign the initial value to the Web page and compare the results, the above error can be quite obvious. However, if you are faced with a database system and you do not see an incorrect result, you may not know why the program does not update the database correctly. To make things worse, if you simply put the value into the database as an integer, you may not find this error until someone tries to query the data.
It is now found that about One-twelveth of the members born in 0月 may be surprising and cause some problems. Remember, not just those who were born in January. The information in the database is incorrect and is true for every member. If there are many applications that can add and modify records in this database, tracking this error can be hard work, especially if you can't find out which program line the error is, but first find out which application it is.
(3) Grasp the use of the date
The error in the date-type data that appears in the above program is not very obvious, regardless of what date is entered in the application, the program code can only give the value in the 0~6 because of the setting in the encoding, especially when converting from VBScript to JScript. In JScript, the Getday function returns the day of the week instead of the day of the month, which is equivalent to the weekday function in VBScript, and the return value of the Getday function is 0 (representing Sunday) to 6 (for Saturday).
Note that the weekday function of VBScript returns 1 (representing Sunday) to 7 (representing Saturday).
Therefore, the correct code for a month's date in JScript by the GETDATE function is:
...
Get the individual date elements
Intday = Datbirthdate.getdate ();
Intmonth = Datbirthdate.getmonth () + 1;
Intyear = Datbirthdate.getyear ();
...
Running this program will get the results you want, as shown in Figure 7-11: