ErrorCodeToString.hpp 886 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #pragma once
  2. #include <string>
  3. //#include "TmplBlockBuffer.tlh"
  4. //#include "TmplBlockBuffer.tli"
  5. // 通过调用 FormtMessage, 把 Win32 错误码转换成字符串
  6. inline std::string ErrorCodeToString (DWORD errorCode)
  7. {
  8. std::string rc;
  9. if (errorCode == 0) errorCode = GetLastError ();
  10. std::string fs = std::to_string (errorCode);
  11. rc += "<Error Code=";
  12. rc += fs;
  13. rc += "> : ";
  14. const int nPreAlloc = 2048;
  15. //ECOM::Utility::TmplUniqueBuffer <char> errmsg;
  16. // auto pszBuffer = errmsg.GetBufferSetCount (nPreAlloc);
  17. std::string errmsg;
  18. errmsg.reserve (nPreAlloc);
  19. auto pszBuffer = errmsg.data ();
  20. auto len = ::FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM,
  21. NULL,
  22. errorCode, // GetLastError (),
  23. MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
  24. (LPTSTR) pszBuffer,
  25. nPreAlloc,
  26. NULL);
  27. rc.append (pszBuffer, len - 2); // -2 : 目的是删除尾部的回车/换行
  28. return std::move (rc);
  29. }