ASP Error

ASPError 对象的九个属性、自定义错误页、错误捕获与日志。

Advanced
Key PointsASPError 只在 IIS 的自定义错误页里可用,能拿到错误码、描述、行号、源文件。

九个属性

PropertyMeaning
ASPCodeIIS 产生的错误码
NumberHRESULT,如 -2147467259
Source产生错误的对象或组件
Category错误来源分类
File出错的文件路径
Line出错的行
Column出错的列
Description错误说明
ASPDescription更详细的 ASP 层说明

自定义错误页

ASP
<%-- error.asp:IIS 里把 500.100 指向这个页面 --%>
<%@ Language="VBScript" CodePage="65001" %>
<%
    Dim e
    Set e = Server.GetLastError()
%>
<!DOCTYPE html>
<html><body>
<h1>出错了</h1>
<p>错误号:<%= e.ASPCode %></p>
<p>文件:<%= e.File %></p>
<p>行号:<%= e.Line %></p>
<%
    ' 详细信息只写日志,不显示给用户
    Dim fso, log
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Set log = fso.OpenTextFile(Server.MapPath("/logs/error.log"), 8, True)
    log.WriteLine Now() & " | " & e.File & ":" & e.Line & " | " & e.Description
    log.Close
    Set log = Nothing
    Set fso = Nothing
%>
</body></html>
Text
IIS 管理器 → 网站 → 错误页 → 编辑功能设置
  ☑ 自定义错误页
  500.100 → URL: /error.asp

Server.GetLastError() returns an ASPError only when IIS invokes the page as an error handler. Called from a normal page it returns Nothing, so e.ASPCode fails with "object not set".

页内错误捕获

ASP
<%
    On Error Resume Next

    Dim conn
    Set conn = Server.CreateObject("ADODB.Connection")
    conn.Open "Provider=SQLOLEDB;Data Source=db;..."

    If Err.Number <> 0 Then
        ' 记录并给用户一个友好提示
        Response.Write "数据库暂时不可用,请稍后再试。"
        ' 详细错误进日志
        Response.Write "<!-- err " & Err.Number & ": " & Err.Description & " -->"
        Err.Clear
    End If

    On Error GoTo 0
%>

On Error Resume Next continues after an error and stores it in the Err object. Call Err.Clear after checking or later checks read a stale error.

Wrapping a whole page in On Error Resume Next is a disaster: one error is swallowed, the rest runs in a broken state, and the symptom is "the page looks fine but nothing was saved". Enable it around specific lines and immediately On Error GoTo 0.

错误页不能泄露什么

ASP
<%-- 危险:把内部信息全暴露 --%>
<p><%= e.File %></p>
<p><%= e.Description %></p>
<p><%= e.Source %></p>
  • 物理路径 —— 暴露服务器目录结构,方便攻击者找上传点
  • SQL 语句 —— ADO 的错误描述里常带完整 SQL
  • 组件版本 —— 帮助攻击者匹配已知漏洞

IIS 的两个开关

Text
ASP → 调试属性
  ☐ 将错误发送到浏览器          ← 生产环境必须关
  ☐ 启用详细 ASP 错误消息        ← 生产环境必须关

With these on, IIS renders error details straight to the browser and skips your custom page. Handy in development, equivalent to publishing your source structure in production.

Friends & Partners