我正在开始我的第一次ASP.NET任务。这是一个网站,我在Visual Studio工作。
我无法弄清楚如何在ExecuteNonQuery失败时显示详细的错误消息。
我正在使用OleDb连接,所以我的猜测是我必须使用OleDbException或OleDbError来获取详细的错误消息。
基本上,问题是 - 如何更新此代码以获得IF ExecuteNonQuery失败的详细错误消息?
string v1 = Request["v1"];
string v2 = Request["v2"];
sql2 = "INSERT INTO table(one, two) VALUES('" + v1 + "', '" + v2 + "')";
System.Data.OleDb.OleDbConnection con2 = new System.Data.OleDb.OleDbConnection();
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/BB/Desktop/Database.mdb";
con2.Open();
OleDbCommand command = new OleDbCommand(sql2, con2);
try
{
command.ExecuteNonQuery();
}
catch
{
Response.Write("Error!");
// detailed error message here?
}
答案 0 :(得分:6)
将您的catch
更改为catch (Exception ex)
,然后您可以使用Response.Write(ex.Message)
理想情况下,对于不同的异常类型,您会有不同的捕获。这是一种捕获所有异常的桶方法。
答案 1 :(得分:0)
更改捕获以捕获(SqlException ex)和catch(异常Exception)
catch (SqlException ex)
{
StringBuilder errorMessages = new StringBuilder();
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #......" + i.ToString() + Environment.NewLine +
"Message:....." + ex.Errors[i].Message + Environment.NewLine +
"LineNumber:.." + ex.Errors[i].LineNumber + Environment.NewLine);
}
WriteToLog(FileLog, "SQL Error message: " + errorMessages.ToString() + Environment.NewLine);
WriteToLog(FileLog, "Process has been finished with errors." + Environment.NewLine);
}
catch (Exception ex)
{
WriteToLog(FileLog, "Error message: " + ex.Message + Environment.NewLine);
WriteToLog(FileLog, "Error stack trace: " + ex.StackTrace + Environment.NewLine);
WriteToLog(FileLog, "Process has been finished with errors." + Environment.NewLine);