#pragma once #define _CRT_SECURE_NO_DEPRECATE #define STRICT #define WIN32_LEAN_AND_MEAN #include #include #include #include #include using namespace std; #include #define WIN_LOG_FILE_NAME "win_err_log.txt" /* ----------------------------------------------------------------- Derived from the KException class to handle exceptions in WinAPI code. Test is overloaded to deal with different datatypes returned by API functions. Usage: e_win.Test(retval, __FILE__, __LINE__, "Function_name"); where e_win is the dummy instance of the exception object and, retval is the return value of the API call. -----------------------------------------------------------------*/ namespace KException { class KWinException : public KExceptionAbstract { protected: public: KWinException(); KWinException(const KWinException&); ~KWinException(); template void SetErrCode(void); template void SetErrCode(int); template void SetErrString(void); template void SetErrString(string); void ConstructErrorMsg(void); void DisplayErrorMsg(void); void WriteErrorMsg(void); template void Test(T test_val, const string file_name, const int line_num, const string func_name); }; template void KWinException:: SetErrCode(void) { err_code = GetLastError(); //Windows API call } template void SetErrCode(int code) { err_code = code; } template void KWinException:: SetErrString(void) { // Output buffer for the FormatMessage fucntion. // This buffer can be a maximum of 64KB. LPVOID msg_buf; TCHAR temp[1000]; size_t temp_len; // Windows API call FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&msg_buf, 0, NULL ); // Write string to a TCHAR buffer, and find its length, // construct a c++ string using the array, // copy string to class data member. StringCchPrintf(temp, sizeof(temp)/sizeof(TCHAR), L"%s", msg_buf); StringCchLength(temp, sizeof(temp)/sizeof(TCHAR), &temp_len); // The string written to temp contains two extra characters at the end // hence 2 is subtracted. // [Why?] string temp_str(&temp[0], &temp[temp_len-2]); err_string = temp_str; } template void KWinException:: SetErrString(string s) { err_string = s; } template void KWinException:: Test(T test_val, const string file_name, const int line_num, const string func_name) { if(test_val == 0) { KWinException ex; ex.SetErrCode(); ex.SetErrString(); ex.SetErrFileName(file_name); ex.SetErrLine(line_num); ex.SetErrFuncName(func_name); throw ex; } } }