ASP技巧研究:ASP Error對象的相關知識

來源:互聯網
上載者:User

  在VBScript中,有一個On Error Resume Next語句,它使指令碼解譯器忽略運行期錯誤並繼續指令碼代碼的執行。接著該指令碼可以檢查Err.Number屬性的值,判別是否出現了錯誤。如果出現錯誤,返回一個非零值。在ASP 3.0中,也可以使用On Error Goto 0“轉回到”預設的錯誤處理。在ASP 2.0中實際也進行這種處理,但是沒有相應文檔說明,這在很多asp資料相關處理檔案中司空見慣,加上On Error Resume Next ,關閉預設的錯誤處理,然後用err抓住,

If Err Then
err.Clear
Response.Write "出現了錯誤!"
Response.End
End If

  為了得到更加詳細的錯誤說明,我們就試試asperror對象吧,它是asp3.0的新對象,它可以通過server對象的getlasterror方法得到,asperror提供了關於asp中發生最後一個錯誤的詳細資料,與VBScript的Err對象不同,不能為查看是否出現了錯誤而隨時調用該方法,只能在一個ASP定製的錯誤網頁中使用。如果像對Err對象進行操作那樣,通過關閉預設的錯誤處理(用On Error Resume Next語句)來使用,則GetLastError方法不能訪問錯誤的詳細資料。
ASPError對象的屬性:
ASPError對象提供了九個屬性說明所出現的錯誤的性質和錯誤源,並返回引發錯誤的實際代碼,其屬性及說明如下:

ASPCode : 整型。由ASP/IIS產生的錯誤號碼,例如0x800A009 
ASPDescription:  字串型。如果這個錯誤是與ASP相關的錯誤,這個屬性是錯誤的詳細說明.例如:All HTTP: HTTP_ACCEPT:*/* HTTP_ACCEPT_LANGUAGE:zh-cn HTTP_CONNECTION:Keep-Alive HTTP_HOST:s HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; (R1 1.5)) ...還有cookie等報告.
Category : 字串型。錯誤來源,即ASP內部指令碼語言、或一個對象.
Column : 整型。產生錯誤的檔案中的字元位置 
Description : 字串型。錯誤的簡短說明
File : 字串型。錯誤出現時正在處理的檔案的名稱
Line : 整型。產生錯誤的檔案中的行號 
Number : 整型。一個標準的COM錯誤碼 
Source : 字串型。引發錯誤的行的實際代碼

ok,這就是9個屬性,使用asperror對象的文法是:

asperror.property
就是這樣:ASPError.ASPCode()
ASPError.ASPDescription()
ASPError.Category()
ASPError.Column()
ASPError.Description()
ASPError.File()
ASPError.Line()
ASPError.Number()
ASPError.Source()

在iis支援的所有目錄下面(或:在編輯了錯誤映射屬性的目錄內)的任一頁面上出現一個與ASP相關的錯誤時,都將載入定製錯誤頁面。實際上,現在已經設定了一個正常的指令碼錯誤陷阱,因為在這個目錄內的任何一個網頁上的ASP運行期錯誤都將觸發定製錯誤頁面,錯誤網頁作為IIS的預設安裝部分,可根據個人情況定製.例如,當我們在一個目錄下面輸入不存在的網頁時,出現404錯誤,當一個404錯誤出現時,使用的頁面是404b.htm,這個檔案包含一個用戶端指令碼代碼部分,它獲得當前文檔的URL(從document對象的url屬性中檢索)並在該頁面中顯示:[html]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html dir=ltr>

<head>
<style> a:link            {font:9pt/11pt 宋體; color:FF0000} a:visited        {font:9pt/11pt 宋體; color:#4e4e4e}
</style>

<META NAME="ROBOTS" CONTENT="NOINDEX">

<title>無法找到網頁</title>

<META HTTP-EQUIV="Content-Type" Content="text-html; charset=gb2312">
<META NAME="MS.LOCALE" CONTENT="ZH-CN">
</head>

<script>
function Homepage(){
<!--
// in real bits, urls get returned to our script like this:
// res://shdocvw.dll/http_404.htm#http://www.DocURL.com/bar.htm

    //For testing use DocURL = "res://shdocvw.dll/http_404.htm#https://www.microsoft.com/bar.htm"
    DocURL = document.URL;

    //this is where the http or https will be, as found by searching for :// but skipping the res://
    protocolIndex=DocURL.indexOf("://",4);

    //this finds the ending slash for the domain server
    serverIndex=DocURL.indexOf("/",protocolIndex + 3);

        //for the href, we need a valid URL to the domain. We search for the # symbol to find the begining
    //of the true URL, and add 1 to skip it - this is the BeginURL value. We use serverIndex as the end marker.
    //urlresult=DocURL.substring(protocolIndex - 4,serverIndex);
    BeginURL=DocURL.indexOf("#",1) + 1;

    urlresult=DocURL.substring(BeginURL,serverIndex);

    //for display, we need to skip after http://, and go to the next slash
    displayresult=DocURL.substring(protocolIndex + 3 ,serverIndex);

    InsertElementAnchor(urlresult, displayresult);
}

function HtmlEncode(text)
{
    return text.replace(/&/g, '&amp').replace(/'/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function TagAttrib(name, value)
{
    return ' '+name+'="'+HtmlEncode(value)+'"';
}

function PrintTag(tagName, needCloseTag, attrib, inner){
    document.write( '<' + tagName + attrib + '>' + HtmlEncode(inner) );
    if (needCloseTag) document.write( '</' + tagName +'>' );
}

function URI(href)
{
    IEVer = window.navigator.appVersion;
    IEVer = IEVer.substr( IEVer.indexOf('MSIE') + 5, 3 );

    return (IEVer.charAt(1)=='.' && IEVer >= '5.5') ?
        encodeURI(href) :
        escape(href).replace(/%3A/g, ':').replace(/%3B/g, ';');
}

function InsertElementAnchor(href, text)
{
    PrintTag('A', true, TagAttrib('HREF', URI(href)), text);
}

//-->
</script>

<body bgcolor="FFFFFF">

<table width="410" cellpadding="3" cellspacing="5">

  <tr>
    <td align="left" valign="middle" width="360">
    <h1 style="COLOR:000000; FONT: 12pt/15pt 宋體"><!--Problem-->無法找到網頁</h1>
    </td>
  </tr>

  <tr>
<td width="400" colspan="2"> <font style="COLOR:000000; FONT: 9pt/11pt 宋體">您正在搜尋的網頁可能已經刪除、更名或暫時不可用。</font></td>
  </tr>

  <tr>
    <td width="400" colspan="2"> <font style="COLOR:000000; FONT: 9pt/11pt 宋體">

    <hr color="#C0C0C0" noshade>

<p>請嘗試下列操作:</p>

    <ul>
<li>如果您在“地址”欄中鍵入了網頁地址,請檢查其拼字是否正確。<br>
      </li>

<li>開啟 <script>
      <!--
      if (!((window.navigator.userAgent.indexOf("MSIE") > 0) && (window.navigator.appVersion.charAt(0) == "2")))
      {
          Homepage();
      }
      //-->
       </script> 首頁,尋找指向所需資訊的連結。</li>

<li>單擊<a href="javascript:history.back(1)">後退</a>按鈕嘗試其他連結。</li>
    </ul>

<h2 style="font:9pt/11pt 宋體; color:000000">HTTP 404 - 無法找到檔案<br> Internet 資訊服務<BR></h2>

    <hr color="#C0C0C0" noshade>

    <p>技術資訊(支援個人)</p>

<ul>
<li>詳細資料:<br><a href="http://www.microsoft.com/ContentRedirect.asp?prd=iis&sbp=&pver=5.0&pid=&ID=404&cat=web&os=&over=&hrd=&Opt1=&Opt2=&Opt3=" target="_blank">Microsoft 支援</a>
</li>
</ul>

    </font></td>
  </tr>

</table>
</body>
</html>
[/html]

當出現錯誤時,錯誤和錯誤網頁檔案之間的映射關係是在每個目錄的properties對話方塊的Custom Errors選項卡中決定的,這在Internet Services Manager裡面的屬性設定,誰有興趣的話就去看看.
定製錯誤網頁顯示ASPError對象屬性的所有值,並通過使用Response.Status方法,把一個HTTP前序狀態訊息返回給用戶端,指明出現了一個錯誤。接著使用GetLastError方法擷取對ASPError對象的一個引用,因此可以訪問錯誤的詳細資料:

 <%
Response.Status = "500 Internal Server Error"
Set objASPError = Server.GetLastError()
%>
Currently executing the page: <B>show_error.asp</B><P>
<B>Error Details:</B><BR>

ASPError.ASPCode = <% = objASPError.ASPCode %><BR>
ASPError.Number = <% = objASPError.Number %> (0x<% = Hex(objASPError.Number) %>)<BR>
ASPError.Source = <% = Server.HTMLEncode(objASPError.Source) %><BR>
ASPError.Category = <% = objASPError.Category %><BR>
ASPError.File = <% = objASPError.File %><BR>
ASPError.Line = <% = objASPError.Line %><BR>
ASPError.Column = <% = objASPError.Column %><BR>
ASPError.Description = <% = objASPError.Description %><BR>
ASPError.ASPDescription = <% = objASPError.ASPDescription %>

<FORM ACTION="<% = Request.ServerVariables("HTTP_REFERER") %>" METHOD="POST">
<INPUT TYPE="SUBMIT" NAME="cmdOK" VALUE=" Return to the previous page  ">
  <P>
</FORM>

如果一個指令碼或ASP錯誤出現在定製錯誤網頁中,IIS將僅僅返回一個與錯誤碼500:100對應的一般性訊息。這可能是指令碼引擎自己的錯誤訊息,或者只是相當簡單的訊息:“Internal Server Error”。不會再次重新載入定製的錯誤網頁。
包含錯誤的網頁的全部環境將傳送給定製錯誤網頁。也就是說,可以使用儲存在任何ASP內部對象集合或屬性中的值。例如,如果檢索來自Request.ServerVariables集合的HTTP_REFERER值,它將反映調用原網頁的網頁(即在錯誤出現之前的網頁)的URL。在伺服器把執行轉到錯誤網頁時,這個值不會發生變化,並且它將不包含當錯誤發生時正在執行的網頁的URL。
同樣,SCRIPT_NAME值將是包含該錯誤的網頁的名字,而不是錯誤網頁的URL。在一個錯誤網頁已經裝入時,通過檢查瀏覽器地址欄中的URL,可以對此進行確認。但是在原網頁的指令碼變數中儲存的值,在定製的錯誤網頁中都是停用。
如果原ASP網頁正在一個事務內運行,即在網頁的最前麵包含有一個<% @TRANSACTION=”…” %>指令,也應該確定是否需要在網頁中採取一些方法,以退出該事務。例如可以調用內建ObjectContext對象的SetAbort方法:
objectContext.SetAbort     
 
嗯,前端時間發過幾千垃圾郵件,全是錯誤處理的

Option Explicit
Response.AddHeader "Status Code", "200" 
Response.AddHeader "Reason", "OK" 
On Error Resume Next
Response.Clear
Dim objError
Set objError = Server.GetLastError()
 
dim objErr, objMail, html
set objErr=Server.GetLastError()
Set objMail = CreateObject("CDONTS.NewMail")
objMail.From = "s1z2d3s1@163.com"
objMail.to= "5do8@5do8.com"
objMail.BodyFormat = 0
objMail.MailFormat = 0
objMail.Subject = "QOP Error 500" 
html = "<font face='Verdana, Arial, Helvetica, sans-serif'><br>"
html = html & "<p>Error occured at: " & now
html = html & "<p>Referred from: " & request.ServerVariables("HTTP_REFERER")
html = html & "<p>Url: " & request.ServerVariables("URL")
html = html & "<p><b>Category: </b></p>" & objErr.Category
html = html & "<p><b>Filename: </b></p>" & objErr.File
html = html & "<p><b>ASP Code: </b></p>" & objErr.ASPCode
html = html & "<p><b>Number: </b></p>" & objErr.Number
html = html & "<p><b>Source: </b></p>" & objErr.Source
html = html & "<p><b>LineNumber: </b></p>" & objErr.Line
html = html & "<p><b>Column: </b></p>" & objErr.Column
html = html & "<p><b>Description: </b></p>" & objErr.Description
html = html & "<p><b>ASP Description: </b></p>" & objErr.ASPDescription
html = html & "<blockquote>" 
html = html & "All HTTP: " & Request.ServerVariables("ALL_HTTP")
html = html & "</blockquote></font>"
objMail.Body = html
objMail.Send 
objErr.clear
Set objMail = Nothing
Set objErr = Nothing
response.write(html)

這個操作起來確實很煩,看看老蓋先生的在500-100.asp裡面寫了寫什麼東西:

<%
  Response.Write objASPError.Category
  If objASPError.ASPCode > "" Then Response.Write ", " & objASPError.ASPCode
  Response.Write " (0x" & Hex(objASPError.Number) & ")" & "<br>"

  Response.Write "<b>" & objASPError.Description & "</b><br>"

  If objASPError.ASPDescription > "" Then Response.Write objASPError.ASPDescription & "<br>"

  blnErrorWritten = False

  ' Only show the Source if it is available and the request is from the same machine as IIS
  If objASPError.Source > "" Then
    strServername = LCase(Request.ServerVariables("SERVER_NAME"))
    strServerIP = Request.ServerVariables("LOCAL_ADDR")
    strRemoteIP =  Request.ServerVariables("REMOTE_ADDR")
    If (strServername = "localhost" Or strServerIP = strRemoteIP) And objASPError.File <> "?" Then
      Response.Write objASPError.File 
      If objASPError.Line > 0 Then Response.Write ", line " & objASPError.Line
      If objASPError.Column > 0 Then Response.Write ", column " & objASPError.Column
      Response.Write "<br>"
      Response.Write "<font style=""COLOR:000000; FONT: 8pt/11pt courier new""><b>"
      Response.Write Server.HTMLEncode(objASPError.Source) & "<br>"
      If objASPError.Column > 0 Then Response.Write String((objASPError.Column - 1), "-") & "^<br>"
      Response.Write "</b></font>"
      blnErrorWritten = True
    End If
  End If

  If Not blnErrorWritten And objASPError.File <> "?" Then
    Response.Write "<b>" & objASPError.File
    If objASPError.Line > 0 Then Response.Write ", line " & objASPError.Line
    If objASPError.Column > 0 Then Response.Write ", column " & objASPError.Column
    Response.Write "</b><br>"
  End If
%>

 此處參考了:ASP 3.0進階編程關於使用ASPError對象的屬性,有以下幾點值得注意的:
· 即使沒有出現錯誤,Number屬性應該一直有一個值。如果ASP網頁調用GetLastError方法時沒有錯誤出現,該屬性的值是0。通常情況下,對ASP指令碼的運行期錯誤,Number屬性返回十六進位的值“0x800A0000”,加上標準的指令碼引擎錯誤碼。例如,前面的例子對“Subscript out of Range”錯誤的傳回值為“0x800A0009”,因為VBScript對該類型錯誤的錯誤碼是“9”。
· 當出現已經過一個錯誤時,Category和Description屬性將一直有一個值。
· APSCode屬性的值由IIS產生,對大多數指令碼錯誤將為空白。更多情況下,涉及外部組件使用出錯時有相應的值。
· ASPDescription屬性的值由ASP預先處理程式產生,而不是由當前正在使用的指令碼引擎產生的,並且對大多數指令碼錯誤而言將是空的。更多情況下,對諸如對ASP內建對象調用無效的方法的錯誤有相應的值。
· File、Source、Line和column屬性僅在錯誤出現時,並且在錯誤的詳細資料是可用的情況下才能進行設定。對一個運行期錯誤,File和Line屬性通常是有效,但是column屬性經常返回-1。當錯誤是一個阻止頁面被ASP處理的語法錯誤,才返回Source屬性。一般在這些情況下,Line和Column屬性是有效。如果把Source屬性的值寫到頁面,明智的辦法是先將該值傳給HTMLEncode,以防在其含有非法的HTML字元。在本章的後面將詳細地討論HTMLEncode方法.

ERR對象

Tips:這是第二次寫這個了,NND,原先寫的重點是ASPError對象的介紹,我現在介紹一下err對象,這是一個很簡單易於操作的對象,let's go.,在asp頁面中.

err對象使用的時候不需要建立執行個體,就是說你要用的時候隨便拿來使用,就像session一樣,不需要像ADODB對象使用的時候Set conn=Server.CreateObject("ADODB.Connection")來建立執行個體,它返回一個錯誤碼,但是Err!=Err.Number,可以用Clear方法清除,以利於下次使用.它主要的是個Description方法,返回的是簡要錯誤說明,這裡一個很經典的例子:

<%@ LANGUAGE="VBscript" %> 
<%Response.Buffer = True 
On Error Resume Next
%>
<%
s="sa"
response.write(Int(s))
If Err.Number <> 0 Then 
Response.Clear 
response.write"發生錯誤:"%> 
<HTML> 
<HEAD> 
<TITLE></TITLE> 
</HEAD> 
<BODY> 
錯誤 Number: <%= Err.Number %><br/> 
錯誤資訊: <%= Err.Description %><br/> 
出錯檔案: <%= Err.Source %><br/> 
出錯行: <%= Err.Line %><br/> 
<%= Err %>
</BODY> 
</HTML> 
<%End If%>

運行一看,囈,Err.Line 為空白,為啥?因為asp的vb編寫的裡面line方法不被支援,這是一個廢的屬性在vb裡面.jscript的支援,要研究的去catch.

值得注意的是要使用err對象的時候,必須加上On Error Resume Next,原來越過asperror對象的異常拋出.

在連結資料庫的時候可以使用error對象: Count屬性:用來統計Errors集合的數目,Item方法:用來指定特定的一個錯誤,文法為Error.Item(number),其中number為一數字。由於Item為預設的方法,所以Error(number)的寫法與前面的寫法是等價的。下面是一段程式。用來列舉Error對象:
 <%
On Error Resume next
Set conn=Server.CreateObject("ADODB.Connection")
Dim i,your_databasepath:your_databasepath="no.mdb"
connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="&server.mappath(your_databasepath)&""
conn.open connstr
if conn.errors.count<>0 then
response.write "連結資料庫失敗<hr/>"
for i =0 to conn.errors.count-1
response.write conn.errors.item(i)&"<hr>"
response.write Err.Description
next
else
response.write "連結資料庫成功"
end if 
conn.close
%>

沒啥差別和err對象,看到比較結果了麼?寒死了,直接用err對象簡單.

一般建議在調試的時候用asperror對象,就是把On Error Resume next 這行rem了,就預設用asperror拋出了.在正式啟動並執行時候,除非特殊要求,可以使用err對象做點事情.轉自:http://www.jzxue.com/Html/asp/2007/9/456KJE91.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.