Search code examples
c#.net-framework-version

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

Solution

  • 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.