2011-01-04 14 views
9

In base a this, non è possibile convertire un codice di errore HRESULT in un codice di errore Win32. Pertanto (almeno la mia comprensione), il mio uso di FormatMessage al fine di generare messaggi di errore (vale a direCome posso (c'è un modo per) convertire un HRESULT in un messaggio di errore specifico del sistema?

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

) non funziona per HRESULT.

Come si generano questi tipi di stringhe di errore specifiche del sistema per HRESULT?

+1

* sempre * utilizzare IErrorInfo di lasciare la fornitura server COM il messaggio di errore. Solo fallback se non lo supporta. La classe _com_error potrebbe essere utile. –

risposta

15

Questa risposta incorpora le idee di Raymond Chen, e correttamente discerne l'HRESULT in entrata, e restituisce una stringa di errore utilizzando la struttura corretta per ottenere il messaggio di errore:

///////////////////////////// 
// 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

Non dimenticare di includere vent

Problemi correlati