【问题标题】:Turning GetLastError() into an exception将 GetLastError() 变成异常
【发布时间】:2011-05-27 09:15:09
【问题描述】:

我有一个 Visual Studio 2008 C++ 项目,它在出现异常错误的情况下使用Win32Exception 类。 Win32Exception 类如下所示:

/// defines an exception based on Win32 error codes. The what() function will
/// return a formatted string returned from FormatMessage()
class Win32Exception : public std::runtime_error
{
public:
    Win32Exception() : std::runtime_error( ErrorMessage( &error_code_ ) )
    {
    };

    virtual ~Win32Exception() { };

    /// return the actual error code
    DWORD ErrorCode() const throw() { return error_code_; };

private:

    static std::string ErrorMessage( DWORD* error_code )
    {
        *error_code = ::GetLastError();

        std::string error_messageA;
        wchar_t* error_messageW = NULL;
        DWORD len = ::FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | 
                                      FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                      FORMAT_MESSAGE_IGNORE_INSERTS,
                                      NULL,
                                      *error_code,
                                      MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
                                      reinterpret_cast< LPWSTR >( &error_messageW ),
                                      0,
                                      NULL );
        if( NULL != error_messageW )
        {
            // this may generate a C4244 warning. It is safe to ignore.
            std::copy( error_messageW, 
                       error_messageW + len, 
                       std::back_inserter( error_messageA ) );
            ::LocalFree( error_messageW );
        }
        return error_messageA;
    };

    /// error code returned by GetLastError()
    DWORD error_code_;

}; // class Win32Exception

该类在使用它的情况下运行良好。我想知道是否有任何明显的情况会失败,我应该知道。欢迎任何其他问题、警告或一般性改进建议。

请注意,boost 库不是此代码的选项。

【问题讨论】:

  • 如果您想知道,这个类也用于没有FormatMessageA 的WindowsMo​​bile。这就是它从 UNICODE 转换为 ASCII 的原因。

标签: c++ exception error-handling


【解决方案1】:
  • 真是巧合!我在所有项目中都使用了类似的代码!这其实是个好主意。

  • 这段代码有问题:

        // this may generate a C4244 warning. It is safe to ignore.
        std::copy( error_messageW, 
                   error_messageW + len, 
                   std::back_inserter( error_messageA ) );
    

    它只是将 WCHAR 转换为字符。您可以明确使用 FormatMessageA 在当前代码页中获取消息(好吧,您不能像您说的那样),或者约定您的所有字符串都是 UTF-8 编码的。我选择了后者,看this为什么。

  • 错误消息本身可能没有用。捕获堆栈跟踪可能是个好主意。

【讨论】:

  • 派生std::runtime_error 的std::exception 将what() 函数定义为const wchar_t* what()。这就是我将字符串转换为 ASCII 的原因。或者你是说我应该使用std::copy()以外的东西来进行字符串转换?我想我可以切换到::wcstombs()。这在当时似乎更容易。
  • 是的,使用 wcstombs、WideCharToMultiByte 或像现在一样复制并验证文本实际上是 ascii。不过这并不重要,因为 FormatMessage 可能会在任何健全的系统上返回 ASCII。
  • @PaulH:它是来自what 的const char *,而不是wchar_t(我希望它可以这样工作)wcstombs 的困难在于你不知道它期望什么源编码,而且你不知道它转换成什么编码。考虑到您无论如何都在使用特定于 Win32 的场景,您不妨只使用 FormatMessageA。
  • @Billy:OP 在对他的帖子的评论中说他不能在 WindowsMo​​bile 上使用 FormatMessageA。
  • @ybungalobill:很有趣。然后是 WideCharToMultiByte。
【解决方案2】:
  • FormatMessage 本身可能会失败。对于这种情况,可能需要一些中性的“代码 %d 的未知错误”。
  • 某些错误代码并非真正的错误 (ERROR_ALREADY_EXISTS),具体取决于用户的预期。
  • 某些系统函数返回它们自己的错误代码(值得注意的例子是SHFileOperation),您必须单独处理这些代码。如果您希望处理它们,那就是。
  • 考虑在异常中包含其他信息:从哪里抛出异常(源文件和行),哪个系统函数导致异常,函数的参数是什么(至少是识别参数,如文件名、句柄值、或一些这样的)。堆栈跟踪也不错。

【讨论】:

  • "Unknown error with code %d" 实际上我认为应该是 %u 或 0x%8x 才真正酷。corner>
【解决方案3】:

我想知道的是如果有 是任何明显的情况,这将 我应该知道的失败。任何 其他陷阱、警告或一般性 改进建议是 欢迎。

我在检索此类消息时遇到的主要问题是ERROR_SUCCESS。当某些操作失败并伴随错误消息“操作成功”时,这是相当令人困惑的。人们不会认为这会发生,但它确实发生了。

我想这是 Dialecticus 所指出的一个特殊情况,即“某些错误代码并不是真正的错误”,但对于大多数这些代码,至少该消息通常是可以接受的。

第二个问题是大多数Windows系统错误信息的末尾都有回车+换行。将消息插入其他文本是有问题的,并且它打破了 C++ 异常消息的约定。所以,删除这些字符是个好主意。

现在,与其重复其他人已经注意到的所有内容,不如简单介绍一下设计。

如果将ErrorMessage 函数公开或移出类,并按值获取错误代码而不是指针参数,则该函数将更加有用。这是保持不同职责分开的原则。促进重复使用。

如果您使用析构函数来释放内存,ErrorMessage 中的代码会更加清晰、安全和高效。然后你也可以直接在return 语句中构造字符串,而不是使用带有反向插入器的复制循环。

干杯,

【讨论】:

    【解决方案4】:

    请注意,如果back_inserter 导致std::bad_alloc 被抛出,则FormatMessage 内部分配的内存会泄漏。

    【讨论】:

    • +1 表示我错过的内存泄漏!但是,您发布链接的代码不是线程安全的,它使用静态变量来存储 what() 的结果。
    • @ybungalobill:是的,它不是线程安全的——我只在单线程应用程序中使用它。 (并且在它旁边的注释中清楚地标记了缺乏线程安全性:P)如果您需要线程安全性,您可以在异常对象本身中存储一个std::string,我选择不为这个特定的库这样做,以便抛出异常时,我不必为 std::string 构造付费。如果您需要线程安全,只需调用GetCharMessage(),它会返回std::string。
    • 抱歉,我在阅读代码时不阅读 cmets:P 讨厌噪音。正确的做法是拥有一个mutable 缓存并在第一次调用what() 时填充它。
    • @ybungalobill:但是你必须为std::string的构建付费,即使你不需要使用错误信息。
    • @TamásSzelei:已更新。谢谢!
    【解决方案5】:

    我最近正在研究一个非常相似的课程,在阅读了这个帖子之后,我试图让复制部分异常安全。我介绍了一个小助手类,它只保存指向::FormatMessage 返回的字符串的指针,并在其析构函数中使用::LocalFree 释放它。不允许复制、分配和移动,以免惹上麻烦。

    这是我想出的全部内容:

    class windows_error {
    public:
        windows_error(wchar_t const* what);
    
        // Getter functions
        unsigned long errorCode() const { return _code; }
        wchar_t const* description() const { return _what; }
        std::wstring errorMessage() const { return _sys_err_msg; }
    private:
        unsigned long _code;
        wchar_t const* _what;
        std::wstring _sys_err_msg;
    };
    
    // This class outsources the problem of managing the string which
    // was allocated with ::LocalAlloc by the ::FormatMessage function.
    // This is necessary to make the constructor of windows_error exception-safe.
    class LocalAllocHelper {
    public:
        LocalAllocHelper(wchar_t* string) : _string(string) { }
        ~LocalAllocHelper() {
            ::LocalFree(_string);
        }
    
        LocalAllocHelper(LocalAllocHelper const& other) = delete;
        LocalAllocHelper(LocalAllocHelper && other) = delete;
        LocalAllocHelper& operator=(LocalAllocHelper const& other) = delete;
        LocalAllocHelper& operator=(LocalAllocHelper && other) = delete;
    
    private:
        wchar_t* _string;
    };
    
    windows_error::windows_error(wchar_t const* what)
        : _code(::GetLastError()),
          _what(what) {
        // Create a temporary pointer to a wide string for the error message
        LPWSTR _temp_msg = 0;
        // Retrieve error message from error code and save the length
        // of the buffer which is being returned. This is needed to 
        // implement the copy and assignment constructor.
        DWORD _buffer_size = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                                              FORMAT_MESSAGE_FROM_SYSTEM |
                                              FORMAT_MESSAGE_IGNORE_INSERTS, 
                                              NULL, _code, 0, _temp_msg, 0, NULL);
    
        if(_buffer_size) {
            // When calling _sys_err_msg.resize an exception could be thrown therefore
            // the _temp_msg needs to be a managed resource.
            LocalAllocHelper helper(_temp_msg);
            _sys_err_msg.resize(_buffer_size + 1);
            std::copy(_temp_msg, _temp_msg + _buffer_size, _sys_err_msg.begin());
        }
        else {
            _sys_err_msg = std::wstring(L"Unknown error. (FormatMessage failed)");
        }
    }
    

    也许这对你们中的一些人有用。

    【讨论】:

      【解决方案6】:

      意识到这是旧的,但至少在 VC++ 2015 中,您可以抛出一个 system_error,它可以使用 system_category() 函数完成所有这些操作:

      try
      {
          throw system_error(E_ACCESSDENIED, system_category(), "Failed to write file");
      }
      catch (exception& ex)
      {
          cout << ex.what();
      }
      

      这将打印:“无法写入文件:访问被拒绝”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 2014-01-17
        • 2013-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-20
        相关资源
        最近更新 更多