Creating extension for multiple Exception

Could someone help me create a simple extension for exception? So that I can always use anywhere. I'm always using exception in all of my process.

Here's the exception that I always used:

try
{

}catch (HttpRequestException ex) { LogsHelper.Error(ex.Message); }
 catch (KeyNotFoundException ex) { LogsHelper.Error(ex.Message); }
 catch (JsonException ex) { LogsHelper.Error(ex.Message); }
 catch (InvalidDataException ex) { LogsHelper.Error(ex.Message); }
 catch (Exception ex) { LogsHelper.Error(ex.Message); }

2 answers

  • answered 2020-09-14 05:36 Tân

    When you use try-catch block with multiple exceptions, you just need to catch the exceptions that you know it may occur.

    The last exception should be used in order to catch another exception that you may be unexpected.

    try
    {
        // do something with http request and get erorr...
    }
    catch (HttpRequestException ex)
    {
        // the error relates to HttpRequest
    
        return "Cannot connect to server...";
    }
    catch (KeyNotFoundException ex)
    {
        // the error relates to some key in some collection
        // that couldn't be found
    
        return "Key is not valid...";
    }
    catch (JsonException ex)
    {
        // the error relates to JSON
        // while you try to parse, serialize, deserialize...
    
        return "Cannot parse to JSON...";
    }
    catch (InvalidDataException ex)
    {
        // the error relates to your data stream
        // it may be invalid format
    
        return "Invalid data format..."
    }
    catch (Exception ex)
    {
        // other exception/error
        // DivideByZeroException
        // NullReferenceException
        // SqlException
        // ...
    
        return "Failed to do something..."
    }
    

    BTW, you can do something/return some data with some specific message...

  • answered 2020-09-14 05:36 Olivier Rogier

    In case you still have the same pattern, you can refactor and create one or more methods to encapsulate the try catch and its variances.

    For example:

    static public bool TryCatch(Action action)
    {
      try
      {
        action();
        return true;
      }
      catch ( HttpRequestException ex ) { LogsHelper.Error(ex.Message); }
      catch ( KeyNotFoundException ex ) { LogsHelper.Error(ex.Message); }
      catch ( JsonException ex ) { LogsHelper.Error(ex.Message); }
      catch ( InvalidDataException ex ) { LogsHelper.Error(ex.Message); }
      catch ( Exception ex ) { LogsHelper.Error(ex.Message); }
      return false;
    }
    

    Usage

    bool result = TryCatch(() =>
    {
      //
    });
    if ( result )
      DoSomeThing();
    else
      DoAnotherThing;
    
    TryCatch(SomeMethod);
    

    The bool is for convenience and can be ommited.

    This limits the use because of the method signature that takes an Action as a parameter but you can create some overloads if really needed...

    For example I regularly use:

    static public bool TryCatch(Action action)
    {
      try
      {
        action();
        return true;
      }
      catch (Exception ex)
      {
        ex.Manage(ShowExceptionMode.None);
        return false;
      }
    }
    
    static public bool TryCatchManage(Action action)
    {
      try
      {
        action();
        return true;
      }
      catch ( Exception ex )
      {
        ex.Manage();
        return false;
      }
    }
    

    Where the Manage methods analyses the exception from the stack to get information like class name, method name, source code file name and line number, shows a message and logs to a roll over file.

    Note: As said by @MichaelRandall, all the catch in your code can be written as

    try
    {
    }
    catch (Exception ex)
    { 
      LogsHelper.Error(ex.Message);
    }
    

    Unless you want to manage each case like exposed by @Tân.