简体   繁体   English

自定义异常消息C#

[英]Custom Exception Messages C#

How do I go about setting a custom error message based on which error is presented? 如何根据出现的错误设置自定义错误消息?

        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();
        }
    }

In this code block, if an SqlException is caught, it's message is displayed in lblMessage. 在此代码块中,如果捕获到SqlException,则其消息将显示在lblMessage中。

The main thing I am looking at is if there is a connection to the database or not. 我正在查看的主要内容是是否存在与数据库的连接。 If there isn't, it results in the following error "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)". 如果没有,则会导致以下错误“建立与SQL Server的连接时发生了与网络相关或特定于实例的错误。找不到服务器或无法访问该服务器。请验证实例名称是否正确以及SQL Server配置为允许远程连接。(提供者:命名管道提供程序,错误:40-无法打开与SQL Server的连接)”。

If error 40 occurs, I want to set lblMessage to "Cannot connect to database", but if a different SqlException occurs, it should post the full error message. 如果发生错误40,我想将lblMessage设置为“无法连接到数据库”,但是如果发生其他SqlException,则它应发布完整的错误消息。

Here is how you deal, 这是您的处理方式,

    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());
    }

Take a look at this MSDN Error handling technique for more information Link 查看此MSDN错误处理技术以获取更多信息链接

You can modify your code like 您可以像这样修改代码

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;
   }
 }

There is another way to achieve same thing like 还有另一种方法可以实现类似

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;
   }
 }

But I will recommend you catching exception with error number because that will be give you clean code and exact error will get caught. 但是我建议您使用错误号捕获异常,因为这将为您提供干净的代码,并且将捕获确切的错误。

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

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