我正在使用带有c#的asp.net开发一个Web应用程序,使用的代码如下所示。
public string fnDisplayManualRecords1(string patid)
{
string cmdString = "select top 1 (patientid) from Patient_Data where PatientID like '"+patid+"%' order by PatientID desc";
con = new SqlConnection(str);
try
{
con.Open();
cmd = new SqlCommand(cmdString, con);
cmd.Parameters.AddWithValue("@patid", patid);
string result = cmd.ExecuteScalar().ToString();
return result;
}
catch (Exception ex)
{
log.Debug("Error: Inside catch block of fnCreateManualRecords");
log.Error("Error msg:" + ex);
log.Error("Stack trace:" + ex.StackTrace);
//transaction.Rollback();
return ex.ToString();
}
finally
{
con.Close();
}
}
这是一个被调用的函数,如下所示,它适用于正确的数据,但当它捕获异常并且它将在下面显示的文本框中显示异常消息
System.NullReferenceException: Object reference not set to an instance of an object. at myConnection.fnDisplayManualRecords1(String patid) in d:\Shreyas\PMS_CMR\pms_production_manual_updation\App_Code\Connection.cs:line 2157
string result = obj.fnDisplayManualRecords1(patid);
txtlast.Text = result.ToString();
现在我只需要将异常消息更改为“No Data Found”而不是上面显示的实际异常消息。
答案 0 :(得分:1)
NullReferenceException 的原因是应检查
返回值为null。不要忘记关闭SqlConnection
作为SqlCommand
:使用构建,恕我直言,是最佳选择。
public string fnDisplayManualRecords1(string patid) {
string cmdString = "select top 1 (patientid) from Patient_Data where PatientID like '"+patid+"%' order by PatientID desc";
using (new SqlConnection(str)) {
try {
con.Open();
using (cmd = new SqlCommand(cmdString, con)) {
cmd.Parameters.AddWithValue("@patid", patid);
Object data = cmd.ExecuteScalar();
// Check if returned value is null: special case
if (Object.ReferenceEquals(null, data))
return "No data found"; // <- Your message here
return data.ToString();
}
}
catch (DataException ex) { // <- Ordinary data (SQL server) errors
log.Debug("Error: Inside catch block of fnCreateManualRecords");
log.Error("Error msg:" + ex);
log.Error("Stack trace:" + ex.StackTrace);
return ex.ToString();
}
}
}
答案 1 :(得分:0)
try
{
// Do stuff
}
catch (Exception ex)
{
// Log error
// Return friendly string
return "No Data Found";
}
答案 2 :(得分:0)
使用自定义消息进行例外处理并将其返回。 :)
try
{
con.Open();
cmd = new SqlCommand(cmdString, con);
cmd.Parameters.AddWithValue("@patid", patid);
string result = cmd.ExecuteScalar().ToString();
return result;
}
catch (Exception ex)
{
log.Debug("Error: Inside catch block of fnCreateManualRecords");
log.Error("Error msg:" + ex);
log.Error("Stack trace:" + ex.StackTrace);
//transaction.Rollback();
//Custom Exception
Exception sqlException= new Exception("No Data Found");
return sqlException;
//return ex.ToString();
}
finally
{
con.Close();
}