简体   繁体   中英

Error message handling due to exceptions

i have a code to restart a service in an event which does other functions too.

I have a try catch in the event for everything within the event like this:

private void btnApply_Click(object sender, EventArgs e)
    {
        try
        {               
            applyChangesAndCheckRestartService();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error loading page.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

private void applyChangesAndCheckRestartService()
    {
        string svrPortNo = CommonCodeClass.getTagValue(CommonCodeClass.xml_SvrPortNoTag, CommonCodeClass.configLocation + CommonCodeClass.configXML);               

        if (!ApplyChangesForSettings())
        {                
            return;
        }

        if (svrPortNo != tbSvrPortNo.Text)
        {               
            CommonCodeClass.CheckToRestartService();
        }
    }

Now if there is an error during ApplyChangesForSettings() i will get an error popup "Error loading page".

If there is an error in CheckToRestartService() i will get the same error because of the try catch.

Is there a better way to handle this.

Like i dont mind the error loading page for ApplyChangesForSettings() but for CheckToRestartService() i would like to see an error like "unable to restart service".

Any suggestions are appreciated. Thanks

internal static void CheckToRestartService()
    {
        DialogResult result = MessageBox.Show(CommonCodeClass.resartServiceMessage, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
        if (result == DialogResult.Yes)
        {
            CommonCodeClass.RestartService(CommonCodeClass.serviceName, 60000);
        }
    }

The fastest way to handle this situation is throwing an exception when someone of your internal methods fails and catch the message in the btnApply_Click.

MessageBox.Show(ex.Message, "Error",  .....);

The rightest way is to create your own exception type and inside the methods, if there is a fail condition throw your own exception. For example create a class like this

public class RestartServiceException : Exception
{
    public RestartServiceException(string message)
        : base(message)
    {
    }
    // You could also write other constructors with different parameters and use internal logic
    // to process your error message
}

and then, use an instance of that class when the fail condition arise inside your CheckToRestartService method

   if(fail == true)
       throw new RestartServiceException("The service could not be started because .....");

You either need to

  • catch the exception in applyChangesAndCheckRestartService
  • or you could pass an enum by ref fe called RestartStatus

     enum RestartStatus{success, unableToRestart, unableToApplySettings}; RestartStatus status = RestartStatus.success; applyChangesAndCheckRestartService(status); if(status != RestartStatus.success) //.... private void applyChangesAndCheckRestartService(out RestartStatus status) { // set the status variable accordingly } 

A third way is to use custom exceptions that you can catch separately.

Well maybe you just need to wrap the different functions with separate try/catch blocks:

    try {
        if (!ApplyChangesForSettings())
           return;
    }
    catch (Exception ex) {
        MessageBox.Show("Error loading page.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    if (svrPortNo != tbSvrPortNo.Text) {      
        try {         
            CommonCodeClass.CheckToRestartService();
        }
        catch (Exception ex) {
            MessageBox.Show("Unable to restart services.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Or, you could consider catching different types of exceptions, if they threw different types:

string errmsg = string.empty;
try { 
    DoSomething();
}
catch (FooException) {
   errmsg = "There was a Foo error";
}
catch (WidgetException) {
   errmsg = "There was a problem with a Widget";
}
catch (Exception ex) {
   errmsg = "General problem: " + ex.Message;
}

if (!string.IsNullOrEmpty(errmsg))
   MessageBox.Show(errmsg);

See also:

Do they throw different exceptions? If they do you could use exception filtering:

private void btnApply_Click(object sender, EventArgs e)
{
    try
    {               
        applyChangesAndCheckRestartService();
    }

    // catch service start exceptions
    catch (InvalidOperationException ioex)
    {
        // display message that couldn't start service
    }

    // catch rest
    catch (Exception ex)
    {
        MessageBox.Show("Error loading page.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

UPDATE this is assuming you're calling something like ServiceController.Start() which throws InvalidOperationException on failure, you could easily throw this yourself on your own error condition or create your own custom exception.

if (/* service didn't start */)
{
    throw new InvalidOperationException("Could not start service.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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