2011-01-04 8 views
9

this'a göre, HRESULT hata kodunu Win32 hata koduna dönüştürmenin bir yolu yoktur. Bu nedenle (en azından benim anlayışıma), sırayla FormatMessage kullanımım hata iletileri (yaniBir HRESULT'ı sisteme özgü bir hata mesajına nasıl dönüştürebilirim (bir yolu var)?

std::wstring Exception::GetWideMessage() const 
{ 
    using std::tr1::shared_ptr; 
    shared_ptr<void> buff; 
    LPWSTR buffPtr; 
    DWORD bufferLength = FormatMessageW(
     FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, 
     NULL, 
     GetErrorCode(), 
     0, 
     reinterpret_cast<LPWSTR>(&buffPtr), 
     0, 
     NULL); 
    buff.reset(buffPtr, LocalFreeHelper()); 
    return std::wstring(buffPtr, bufferLength); 
} 

) HRESULTs için çalışmaz üretmek için.

HRESULT'lar için bu tür sisteme özgü hata dizelerini nasıl oluştururum?

+1

* Her zaman * COM sunucu kaynağını izin IErrorInfo kullanmak hata mesajı. Sadece desteklemiyorsa geri dönüş. _com_error sınıfı yardımcı olabilir. –

cevap

15

Bu cevap Raymond Chen'in fikirleri birleştirir ve doğru gelen HRESULT discerns ve hata mesajı almak için doğru tesisi kullanarak bir hata dize döndürür:

///////////////////////////// 
// ComException 

CString FormatMessage(HRESULT result) 
{ 
    CString strMessage; 
    WORD facility = HRESULT_FACILITY(result); 
    CComPtr<IErrorInfo> iei; 
    if (S_OK == GetErrorInfo(0, &iei) && iei) 
    { 
     // get the error description from the IErrorInfo 
     BSTR bstr = NULL; 
     if (SUCCEEDED(iei->GetDescription(&bstr))) 
     { 
      // append the description to our label 
      strMessage.Append(bstr); 

      // done with BSTR, do manual cleanup 
      SysFreeString(bstr); 
     } 
    } 
    else if (facility == FACILITY_ITF) 
    { 
     // interface specific - no standard mapping available 
     strMessage.Append(_T("FACILITY_ITF - This error is interface specific. No further information is available.")); 
    } 
    else 
    { 
     // attempt to treat as a standard, system error, and ask FormatMessage to explain it 
     CString error; 
     CErrorMessage::FormatMessage(error, result); // <- This is just a wrapper for ::FormatMessage, left to reader as an exercise :) 
     if (!error.IsEmpty()) 
      strMessage.Append(error); 
    } 
    return strMessage; 
} 
+0

'u dahil etmeyi unutmayın. – vent

İlgili konular