繁体   English   中英

自定义异常消息C#

[英]Custom Exception Messages C#

如何根据出现的错误设置自定义错误消息?

        protected void btnNew_Click(object sender, EventArgs e)
    {
        Clear();
        SqlCommand command = conn.CreateCommand();
        SqlDataReader reader;
        try
        {
            command.CommandText = "GetMax";
            command.CommandType = CommandType.StoredProcedure;
            conn.Open();
            reader = command.ExecuteReader();                
            while (reader.HasRows)
            {
                while (reader.Read())
                {
                    int CustMax = reader.GetInt32(0);
                    CustMax++;
                    txtCustID.Text = CustMax.ToString();
                }
                reader.NextResult();
            }
            reader.Dispose();
        }
        catch (SqlException ex)
        {
            lblMessage.Text = ex.Message;

        }
        finally
        {
            command.Dispose();
            conn.Dispose();
        }
    }

在此代码块中,如果捕获到SqlException,则其消息将显示在lblMessage中。

我正在查看的主要内容是是否存在与数据库的连接。 如果没有,则会导致以下错误“建立与SQL Server的连接时发生了与网络相关或特定于实例的错误。找不到服务器或无法访问该服务器。请验证实例名称是否正确以及SQL Server配置为允许远程连接。(提供者:命名管道提供程序,错误:40-无法打开与SQL Server的连接)”。

如果发生错误40,我想将lblMessage设置为“无法连接到数据库”,但是如果发生其他SqlException,则它应发布完整的错误消息。

这是您的处理方式,

    catch (SqlException ex)
    {
        if(ex.Number == 40 ) // or Use whatever the number it returns for the relevant error
        {
             MessageBox.Show("Relevant SQL Error Occured");
        }
        else
        {
             MessageBox.Show("None Relevant SQL Error Occured:" + ex.toString());
        }
    }
    catch(Exception ex)// All other non sql errors
    {
        MessageBox.Show(ex.toString());
    }

查看此MSDN错误处理技术以获取更多信息链接

您可以像这样修改代码

catch (SqlException ex)
 {
    if(ex.Number == 40) // 40 is specific key for network issue
    {
      lblMessage.Text = "Cannot connect to database"  
    }
   else
   { 
    lblMessage.Text = ex.Message;
   }
 }

还有另一种方法可以实现类似

catch ((SqlException ex) {
if (ex.Message.Contains("A network-related or instance-specific error specific"))//Put the matching text here  
{
     lblMessage.Text = "Cannot connect to database" 
}
else
   { 
    lblMessage.Text = ex.Message;
   }
 }

但是我建议您使用错误号捕获异常,因为这将为您提供干净的代码,并且将捕获确切的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM