C# 通过消息捕获异常

C# Catching an exception by message

我需要用我的自定义异常消息更改特定的系统异常消息。

捕获异常并在 catch 块内检查系统异常消息是否与特定字符串匹配并且如果匹配则抛出我的自定义异常是一种不好的做法吗?

try
{
    ...
}
catch (System.Security.Cryptography.CryptographicException ex)
{
    if (ex.Message.Equals("The specified network password is not correct.\r\n", StringComparison.InvariantCultureIgnoreCase))
        throw new Exception("Wrong Password");
    else
        throw ex;
}

或者有没有更好的方法来实现这个。

在 catch 语句中抛出异常本质上没有错。但是,有几点需要牢记:

使用“throw”而不是“throw ex”重新抛出异常,否则您将丢失堆栈跟踪。

来自[创建和抛出异常] 1

Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.

如果 CrytographicException 确实不适合您,您可以创建一个特定的异常 class 来表示无效密码:

try
{
    ...
}
catch (System.Security.Cryptography.CryptographicException ex)
{
    if (ex.Message.Equals("The specified network password is not correct.\r\n",
            StringComparison.InvariantCultureIgnoreCase))
        throw new InvalidPasswordException("Wrong Password", ex);
    else
        throw;
}

请注意原始异常是如何保留在新的 InvalidPasswordException 中的。

要在检查消息时保存展开堆栈,您可以使用用户过滤的异常处理程序 - https://docs.microsoft.com/en-us/dotnet/standard/exceptions/using-user-filtered-exception-handlers。这将为未过滤的异常维护堆栈跟踪。

try
{
    // ...
}
catch (System.Security.Cryptography.CryptographicException ex) when (ex.Message.Equals("The specified network password is not correct.\r\n", 
StringComparison.InvariantCultureIgnoreCase))
{
    throw new InvalidPasswordException("Wrong Password", ex);
}