---
title: llarp/win32/exception.hpp

---

# llarp/win32/exception.hpp



## Namespaces

| Name           |
| -------------- |
| **[llarp](Namespaces/namespacellarp.md)** <br>[crypto.hpp] |
| **[llarp::win32](Namespaces/namespacellarp_1_1win32.md)**  |

## Classes

|                | Name           |
| -------------- | -------------- |
| class | **[llarp::win32::error](Classes/classllarp_1_1win32_1_1error.md)**  |




## Source code

```cpp
#pragma once

#include <array>
#include <string>
#include <windows.h>
#include <stdexcept>

#include <llarp/util/str.hpp>

namespace llarp::win32
{
  namespace
  {
    inline std::string
    error_to_string(DWORD err)
    {
      // mostly yoinked from https://stackoverflow.com/a/45565001
      LPTSTR psz{nullptr};
      const DWORD cchMsg = FormatMessage(
          FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS
              | FORMAT_MESSAGE_ALLOCATE_BUFFER,
          nullptr,
          err,
          MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
          reinterpret_cast<LPTSTR>(&psz),
          0,
          nullptr);

      if (cchMsg <= 0)
      {
        // cannot get message for error, reset the last error here so it does not propagate
        ::SetLastError(0);
        return "unknown error";
      }

      auto deleter = [](void* p) { ::LocalFree(p); };
      std::unique_ptr<TCHAR, decltype(deleter)> ptrBuffer{psz, deleter};
      return std::string{ptrBuffer.get(), cchMsg};
    }
  }  // namespace

  class error : public std::runtime_error
  {
   public:
    error(std::string msg) : error{GetLastError(), std::move(msg)}
    {}

    explicit error(DWORD err, std::string msg)
        : std::runtime_error{fmt::format("{}: {} (code={})", msg, error_to_string(err), err)}
    {}
  };
}  // namespace llarp::win32
```


-------------------------------

Updated on 2022-08-31 at 12:13:02 +0000
