add new exception logic

This commit is contained in:
2025-09-19 00:39:21 +03:00
parent a76aadc068
commit 1604577286
4 changed files with 36 additions and 29 deletions

View File

@@ -17,25 +17,18 @@ auto main(int argc, char *argv[]) -> int
e.set("double", 1.23); e.set("double", 1.23);
e.set("file", std::filesystem::path("/tes/path/to_file.txt")); e.set("file", std::filesystem::path("/tes/path/to_file.txt"));
// struct user_type
// {
// int i = 1;
// std::string str = "user type";
//
// auto get_logger_data()
// {
// return std::make_tuple(i, str);
// }
// } ut;
//
// e.set("user type", ut);
throw e; throw e;
} }
catch(hack::exception& e) catch(hack::exception& e)
{ {
hack::log().no_info();
hack::error()(e);
hack::log()(e); hack::log()(e);
hack::log().reset();
} }
hack::log().reset();
return 0; return 0;
} }

View File

@@ -4,15 +4,22 @@
#include <any> #include <any>
#include <unordered_map> #include <unordered_map>
#include "hack/exception/title.hpp" #include "hack/exception/title.hpp"
#include "hack/patterns/identificator.hpp"
namespace hack namespace hack
{ {
class exception class exception : public patterns::identificator<>
{ {
using LOCATION = std::source_location; using LOCATION = std::source_location;
public: public:
exception(const LOCATION loc = LOCATION::current()) : m_location { loc } {} exception(const LOCATION loc = LOCATION::current()) : m_location { loc } {}
exception(const exception& e) noexcept : m_service { e.m_service },
m_system_error { e.m_system_error },
m_title { e.m_title },
m_description { e.m_description },
m_location { e.m_location },
m_data { e.m_data } {}
~exception() = default; ~exception() = default;
public: public:

View File

@@ -22,16 +22,17 @@ namespace hack
public: public:
void set_location(std::source_location location) { m_location = location; } void set_location(std::source_location location) { m_location = location; }
void set_devider(std::string devider) { m_devider = devider; } void set_devider(std::string devider) { m_devider = devider; }
void no_func() { m_no_func = true; };
void no_file() { m_no_file = true; } void no_file() { m_no_file = true; }
void no_func() { m_no_func = true; };
void no_row() { m_no_row = true; } void no_row() { m_no_row = true; }
void no_info() { no_file(); no_func(); no_row(); }
void bool_as_number() { m_bool_as_number = true; } void bool_as_number() { m_bool_as_number = true; }
void reset() void reset()
{ {
m_no_func = m_base_config.m_no_func;
m_devider = m_base_config.m_devider;
m_no_file = m_base_config.m_no_file; m_no_file = m_base_config.m_no_file;
m_no_func = m_base_config.m_no_func;
m_no_row = m_base_config.m_no_row; m_no_row = m_base_config.m_no_row;
m_devider = m_base_config.m_devider;
m_bool_as_number = m_base_config.m_bool_as_number; m_bool_as_number = m_base_config.m_bool_as_number;
} }
@@ -53,8 +54,8 @@ namespace hack
// настройки по умолчанию // настройки по умолчанию
struct config struct config
{ {
bool m_no_func = false; // показывать/не показывать название функции в выоде логов
bool m_no_file = false; // показывать/не показывать название файла/пути в выоде логов bool m_no_file = false; // показывать/не показывать название файла/пути в выоде логов
bool m_no_func = false; // показывать/не показывать название функции в выоде логов
bool m_no_row = false; // показывать/не показывать номер строки в выоде логов bool m_no_row = false; // показывать/не показывать номер строки в выоде логов
bool m_bool_as_number = false; // показывет bool как число или как текст (0, false); bool m_bool_as_number = false; // показывет bool как число или как текст (0, false);
std::string m_devider = " "; // разделитель по умолчанию std::string m_devider = " "; // разделитель по умолчанию
@@ -225,11 +226,15 @@ namespace hack
{ {
auto loc = e.get_location(); auto loc = e.get_location();
std::cout << utils::color::bold << utils::color::red; std::cout << utils::color::bold << utils::color::red;
std::cout << "exception: ";
std::cout << utils::color::reset; std::cout << utils::color::reset;
std::cout << "{ "; // в скобочках указывается строка и уникальный id исключения
std::cout << "location: " << loc.file_name() << "[" << loc.line() << "]"; // это id при копировании исключения изменяется, так работает паттерн identificator
std::cout << " }" << std::endl; // т.е. следить и думать что каждое созданное исключение - это увеличение на 1 идентификатора
// так себе затея !!!
std::cout << " " << loc.file_name() << utils::color::bold << utils::color::blue << "[" << loc.line() << "," << e.get_id() << "]: " << utils::color::reset << std::endl;
std::cout << utils::color::bold << utils::color::gray;
std::cout << " > ";
std::cout << utils::color::reset;
const auto& data = e.get(); const auto& data = e.get();
bool first = true; bool first = true;
for (const auto& [key, value] : data) for (const auto& [key, value] : data)
@@ -287,7 +292,6 @@ namespace hack
std::cout << utils::color::reset; std::cout << utils::color::reset;
} }
} }
std::cout << " }";
} }
private: private:

View File

@@ -4,7 +4,6 @@
#include <atomic> #include <atomic>
#include <type_traits> #include <type_traits>
#include <limits> #include <limits>
#include "hack/logger/logger.hpp"
namespace hack::patterns namespace hack::patterns
{ {
@@ -24,13 +23,12 @@ namespace hack::patterns
public: public:
/// @brief Конструктор по умолчанию - генерирует новый уникальный ID /// @brief Конструктор по умолчанию - генерирует новый уникальный ID
identificator() noexcept : m_id(next_id()) {} identificator() noexcept : m_id{ next_id() } {}
/// @brief Конструктор копирования - создает новый ID (не копирует старый!) /// @brief Конструктор копирования - создает новый ID (не копирует старый!)
identificator(const identificator&) noexcept : m_id(next_id()) {} identificator(const identificator&) noexcept : m_id{ next_id() } {}
/// @brief Конструктор перемещения - создает новый ID identificator(identificator&& idtf) noexcept : m_id{ idtf.get_id() } {}
identificator(identificator&&) noexcept : m_id(next_id()) {}
/// @brief Оператор присваивания - не меняет ID объекта! /// @brief Оператор присваивания - не меняет ID объекта!
identificator& operator=(const identificator&) noexcept { return *this; } identificator& operator=(const identificator&) noexcept { return *this; }
@@ -45,14 +43,19 @@ namespace hack::patterns
T get_id() const noexcept { return m_id; } T get_id() const noexcept { return m_id; }
protected:
// бывает нужно принудительно установить id, например при копировании в наследовании
// см. exception
void set_id(T new_id) { m_id = new_id; }
private: private:
/// @brief Генерация следующего уникального ID /// @brief Генерация следующего уникального ID
static T next_id() noexcept { static T next_id() noexcept
{
T new_id = m_counter.fetch_add(1, std::memory_order_relaxed); T new_id = m_counter.fetch_add(1, std::memory_order_relaxed);
// Обработка переполнения - циклическое повторение // Обработка переполнения - циклическое повторение
if (new_id == std::numeric_limits<T>::max()) if (new_id == std::numeric_limits<T>::max())
{ {
hack::warn()("Identificator is overflow limminent...");
// Можно бросить исключение или сбросить счетчик // Можно бросить исключение или сбросить счетчик
// В данном случае циклически повторяем // В данном случае циклически повторяем
m_counter.store(1, std::memory_order_relaxed); m_counter.store(1, std::memory_order_relaxed);