errors 0.6.3
Loading...
Searching...
No Matches
error_ptr.hpp
1#pragma once
2
3#include <memory>
4#include <utility>
5
6#include "errors/error.hpp"
7
8namespace errors
9{
10
13class error_ptr : public std::unique_ptr<error> {
14 public:
15 using std::unique_ptr<error>::unique_ptr;
16
25 template <typename E>
26 [[nodiscard]]
27 bool is() const
28 {
29 static_assert(std::is_base_of_v<error, E>);
30
31 auto current = this->get();
32 while (current != nullptr) {
33 if (dynamic_cast<const E *>(current) != nullptr) {
34 return true;
35 }
36
37 current = current->cause().get();
38 }
39 return false;
40 }
41
52 template <typename E>
53 [[nodiscard]]
54 const E *as() const
55 {
56 static_assert(std::is_base_of_v<error, E>);
57
58 auto current = this->get();
59 while (current != nullptr) {
60 auto result = dynamic_cast<const E *>(current);
61 if (result != nullptr) {
62 return result;
63 }
64
65 current = current->cause().get();
66 }
67 return nullptr;
68 }
69
71 template <typename E>
72 [[nodiscard]]
73 E *as()
74 {
75 return const_cast<E *>(std::as_const(*this).as<E>());
76 }
77};
78static_assert(!std::is_abstract<error_ptr>());
79}
80
81#if not defined(ERRORS_DISABLE_OSTREAM)
82
83#include <cassert>
84#include <ostream>
85
86inline std::ostream &operator<<(std::ostream &os, const errors::error_ptr &err)
87{
88 const auto *current = err.get();
89
90 if (!current) {
91 os << "no error";
92 return os;
93 }
94
95 bool printed = false;
96
97 while (current != nullptr) {
98 if (printed) {
99 os << ": ";
100 printed = false;
101 }
102
103 auto what = current->what();
104 assert(what);
105 if (what[0] != '\0') {
106 os << what;
107 printed = true;
108 }
109
110 current = current->cause().get();
111 }
112
113 return os;
114}
115#endif
Smart pointer to errors::error with some utility member functions.
Definition error_ptr.hpp:13
E * as()
Looking up error in causes.
Definition error_ptr.hpp:73
const E * as() const
Looking up error in causes.
Definition error_ptr.hpp:54
bool is() const
Check if the error is caused by some kind of errors::error recursively.
Definition error_ptr.hpp:27
Interface representing an error.
Definition error.hpp:20