2011-02-10 109 views
0

我在我的global.ascx中有下面的代码,当我点击一个生成错误按钮的代码运行,但似乎失败的插入到数据库中的错误。为什么我的global.asax错误处理程序无法正常工作?

我想将错误保存到数据库并重定向到default.aspx。

很标准的东西。

我得到的错误是:exe.Message =“System'附近的语法不正确。” (看起来像somethign与global.asx使用的SQL对象)

void Application_Error(object sender, EventArgs e) 
    { 
     // Code that runs when an unhandled error occurs 
     Exception ex = Server.GetLastError(); 

     StringBuilder theBody = new StringBuilder();   
     theBody.Append("Error Message: " + ex.ToString() + "\n"); 


     Server.ClearError(); 

     try 
    { 
     string sSQL = "INSERT INTO PMISwebErr VALUES ('" + theBody.ToString() + "', GETDATE())"; 

     using (System.Data.SqlClient.SqlConnection con = STAR.Global.GetConnection()) 
     { 
      System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sSQL, con); 
      cmd.CommandType = System.Data.CommandType.Text; 
      cmd.ExecuteScalar(); 
     } 


     Response.Redirect("~/default.aspx?Err=sysError"); 
    } 
    catch (Exception exe) { 
     Response.Redirect("~/default.aspx?Err="+ exe.Message.ToString()); 
    } 

    } 

的问题是在另外的错误消息。它有一个打破SQL的单引号。的代码获得该值作为在此行的结果:

theBody.Append("Error Message: " + ex.ToString() + "\n"); 

sSQL =“INSERT INTO PMISwebErr VALUES ('URL: http://localhost:14854/PMIS/Default.aspx \ nReferer: http://localhost:14854/PMIS/Default.aspx \ NIP: 127.0.0.1 \ n错误消息:System.Web.HttpUnhandledException: 异常类型 'System.Web.HttpUnhandledException' 的是三...

这是实际值从我的快速手表看起来很奇怪,最后看到......。

+0

你的文件实际上叫做`global.ascx`,还是它真的是`global.asax`? – 2011-02-10 15:57:01

+0

如果错误与数据库有关,该怎么办? – 2011-02-10 16:01:14

+0

这是什么SQL字符串(有没有任何未转义的引号?),你会得到任何错误(你看到新的错误,当你删除重定向?) – 2011-02-10 16:03:59

回答

0

正如@ScottE早有预料,你有引号的问题。字符串被单引号包围,但里面是文本Exception of type 'System.Web..,它在不需要它的地方添加引号。

解决方案?使用参数并让驱动程序处理这些引号。

相关问题