SFTK/include/exceptions.hpp

70 lines
1.8 KiB
C++
Raw Normal View History

2024-08-03 04:11:49 +08:00
#ifndef EXCEPTIONS_HPP
#define EXCEPTIONS_HPP
#include <exception>
#include <sstream>
#include <iomanip>
namespace sftk
{
/**
* @brief # SFTK exceptions super class
*
* @tparam T - The SFTK object types
*/
template <class T>
class SFTKException : public std::exception
{
public:
SFTKException(T *obj) : sftkObj(obj) {}
/**
* @brief # Address formatter
*
* This formatter function use 16 `*`s as address placeholder.
*
* When throwing an exception, Exceptions can use placeholder with this function
* to fill the `what()` message. So the reported exception can tell where the crashed
* SFTK object at.
*
* # Example
*
* ```c
* const char *SomeException::what() const noexcept
* {
* static char msg[] = "sftk::SomeClass 0x********_******** reported an exception.";
* SFTKException::formatAddress(msg, sizeof(msg));
* return const_cast<SomeClass *>(msg);
2024-08-03 04:11:49 +08:00
* }
* ```
*
* @param msg exception message
* @param len message length
*/
2024-08-20 10:39:38 +08:00
void formatAddress(char *msg, int len) const noexcept
2024-08-03 04:11:49 +08:00
{
2024-08-20 10:39:38 +08:00
auto ptr = reinterpret_cast<uintptr_t>(sftkObj);
while (--len >= 0)
2024-08-03 04:11:49 +08:00
{
2024-08-20 10:39:38 +08:00
if (msg[len] == '*')
2024-08-03 04:11:49 +08:00
{
2024-08-20 10:39:38 +08:00
auto bit = ptr-- & 0xf;
if (bit < 10)
{
bit += '0';
}
else
{
bit -= 10 - 'a';
}
msg[len] = bit;
2024-08-03 04:11:49 +08:00
}
}
}
private:
T *sftkObj;
};
};
#endif