AUI Framework  develop
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
AException.h
1/*
2 * AUI Framework - Declarative UI toolkit for modern C++20
3 * Copyright (C) 2020-2024 Alex2772 and Contributors
4 *
5 * SPDX-License-Identifier: MPL-2.0
6 *
7 * This Source Code Form is subject to the terms of the Mozilla Public
8 * License, v. 2.0. If a copy of the MPL was not distributed with this
9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 */
11
12#pragma once
13#include <exception>
14
15#include "AString.h"
16#include "AUI/Reflect/AReflect.h"
17#include <AUI/Common/AVector.h>
18#include <AUI/Platform/AStacktrace.h>
19#include <AUI/Traits/strings.h>
20
28class API_AUI_CORE AException : public std::exception {
29 mutable AOptional<std::string> mMessage;
30
31public:
32 AException() : mStacktrace(AStacktrace::capture(2)) {}
33 AException(AStacktrace stacktrace) : mStacktrace(std::move(stacktrace)) {}
34
35 AException(const AString& message) : AException() { mMessage = message.toStdString(); }
36
37 AException(const AException& exception) = default;
38 AException(AException&& exception) noexcept = default;
39
40 AException(const AString& message, std::exception_ptr causedBy, AStacktrace stacktrace = AStacktrace::capture(2))
41 : mStacktrace(std::move(stacktrace)), mCausedBy(std::move(causedBy)) { // NOLINT(*-throw-keyword-missing)
42 mMessage = message.toStdString();
43 }
44
45 virtual AString getMessage() const noexcept { return mMessage ? mMessage->c_str() : "<no message>"; }
46
47 ~AException() noexcept override = default;
48
49 const char* what() const noexcept override {
50 if (!mMessage)
51 mMessage = getMessage().toStdString();
52 return mMessage->c_str();
53 }
54
55 const AStacktrace& stacktrace() const noexcept { return mStacktrace; }
56
57 [[nodiscard]]
58 const std::exception_ptr& causedBy() const noexcept {
59 return mCausedBy;
60 }
61
62private:
63 AStacktrace mStacktrace;
64 std::exception_ptr mCausedBy;
65};
66
67inline std::ostream& operator<<(std::ostream& o, const AException& e) noexcept {
68 o << "(" << AReflect::name(&e) << ") " << e.getMessage() << std::endl << e.stacktrace();
69 if (e.causedBy()) {
70 o << "Caused by: ";
71 try {
72 std::rethrow_exception(e.causedBy());
73 } catch (const AException& e) {
74 o << e;
75 } catch (const std::exception& e) {
76 o << e.what();
77 } catch (...) {
78 o << "unknown exception";
79 }
80 }
81 return o;
82}
Abstract AUI exception.
Definition AException.h:28
Utility wrapper implementing the stack-allocated (fast) optional idiom.
Definition AOptional.h:32
Stacktrace consisting of a collection of stack function frames.
Definition AStacktrace.h:28
static AStacktrace capture(unsigned skipFrames=0, unsigned maxFrames=128) noexcept
Creates stacktrace of the current thread.
Definition AStacktraceImpl.cpp:156
Represents a Unicode character string.
Definition AString.h:37
std::string toStdString() const noexcept
Definition AString.cpp:338