为多个异常创建扩展

Creating extension for multiple Exception

有人可以帮我创建一个简单的异常扩展吗?这样我就可以随时随地使用。 我总是在我的所有过程中使用异常。

这是我一直使用的例外情况:

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

当您使用带有多个异常的 try-catch 块时,您只需要捕获您知道它可能发生的异常。

应使用最后一个异常,以捕获您可能意想不到的另一个异常。

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..."
}

顺便说一句,您可以 something/return 一些带有特定消息的数据...

如果您仍然有相同的模式,您可以重构并创建一个或多个方法来封装 try catch 及其变体。

例如:

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

用法

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

TryCatch(SomeMethod);

布尔值是为了方便,可以省略。

这限制了使用,因为方法签名采用 Action 作为参数,但如果确实需要,您可以创建一些重载...

例如我经常使用:

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

其中 Manage 方法分析堆栈中的异常以获取 class 名称、方法名称、源代码文件名和行号等信息,显示消息并记录到滚动文件。

注意:正如@MichaelRandall 所说,您代码中的所有捕获都可以写成

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

除非您想像@Tân 所公开的那样管理每个案例。