AUI Framework  master
Cross-platform module-based framework for developing C++20 desktop applications
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{
30 mutable AOptional<std::string> mMessage;
31public:
32 AException(): mStacktrace(AStacktrace::capture(2)) {
33
34 }
35 AException(AStacktrace stacktrace): mStacktrace(std::move(stacktrace)) {
36
37 }
38
39 AException(const AString& message)
40 : AException()
41 {
42 mMessage = message.toStdString();
43 }
44
45 AException(const AString& message, std::exception_ptr causedBy, AStacktrace stacktrace = AStacktrace::capture(2))
46 : mCausedBy(std::move(causedBy)),
47 mStacktrace(std::move(stacktrace))
48 {
49 mMessage = message.toStdString();
50 }
51
52 virtual AString getMessage() const noexcept {
53 return mMessage ? mMessage->c_str() : "<no message>";
54 }
55
56 virtual ~AException() noexcept = default;
57
58 const char* what() const noexcept override {
59 if (!mMessage) mMessage = getMessage().toStdString();
60 return mMessage->c_str();
61 }
62
63 const AStacktrace& stacktrace() const noexcept {
64 return mStacktrace;
65 }
66
67 [[nodiscard]]
68 const std::exception_ptr& causedBy() const noexcept {
69 return mCausedBy;
70 }
71
72private:
73 AStacktrace mStacktrace;
74 std::exception_ptr mCausedBy;
75
76};
77
78inline std::ostream& operator<<(std::ostream& o, const AException& e) noexcept {
79 o << "("
80 << AReflect::name(&e)
81 << ") "
82 << e.getMessage()
83 << std::endl
84 << e.stacktrace();
85 if (e.causedBy()) {
86 o << "Caused by: ";
87 try {
88 std::rethrow_exception(e.causedBy());
89 } catch (const AException& e) {
90 o << e;
91 } catch (const std::exception& e) {
92 o << e.what();
93 } catch (...) {
94 o << "unknown exception";
95 }
96 }
97 return o;
98}
Abstract AUI exception.
Definition: AException.h:29
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