ExceptionHelper.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace Helper
  4. {
  5. public static class ExceptionHelper
  6. {
  7. private const int E_NOTIMPL = unchecked((int)0x80004001);
  8. private const int E_OUTOFMEMORY = unchecked((int)0x8007000E);
  9. private const int E_INVALIDARG = unchecked((int)0x80070057);
  10. private const int E_POINTER = unchecked((int) 0x80004003);
  11. private const int E_PENDING = unchecked((int)0x8000000A);
  12. private const int E_FAIL = unchecked((int)0x80004005);
  13. public static void CheckLastError()
  14. {
  15. int hr = Marshal.GetLastWin32Error();
  16. if ((hr == E_PENDING) || (hr == E_FAIL))
  17. {
  18. // Ignore E_PENDING/E_FAIL - We use this to indicate no pending or missed frames
  19. return;
  20. }
  21. if (hr < 0)
  22. {
  23. Exception exception = Marshal.GetExceptionForHR(hr);
  24. string message = string.Format("This API has returned an exception from an HRESULT: 0x{0:X}", hr);
  25. switch (hr)
  26. {
  27. case E_NOTIMPL:
  28. throw new NotImplementedException(message, exception);
  29. case E_OUTOFMEMORY:
  30. throw new OutOfMemoryException(message, exception);
  31. case E_INVALIDARG:
  32. throw new ArgumentException(message, exception);
  33. case E_POINTER:
  34. throw new ArgumentNullException(message, exception);
  35. default:
  36. throw new InvalidOperationException(message, exception);
  37. }
  38. }
  39. }
  40. }
  41. }