QXmpp Version: 1.15.1
Loading...
Searching...
No Matches
QXmppError.h
1// SPDX-FileCopyrightText: 2022 Linus Jahn <lnj@kaidan.im>
2//
3// SPDX-License-Identifier: LGPL-2.1-or-later
4
5#ifndef QXMPPERROR_H
6#define QXMPPERROR_H
7
8#include "QXmppGlobal.h"
9
10#include <any>
11#include <optional>
12
13class QFileDevice;
14class QIODevice;
15class QNetworkReply;
16
17struct QXMPP_EXPORT QXmppError {
18 QString description;
19 std::any error;
20
21 static QXmppError fromIoDevice(const QIODevice &device);
22 static QXmppError fromNetworkReply(const QNetworkReply &reply);
23 static QXmppError fromFileDevice(const QFileDevice &file);
24
25 bool isFileError() const;
26 bool isNetworkError() const;
27 bool isStanzaError() const;
28
29 template<typename T>
30 bool holdsType() const
31 {
32 return error.type().hash_code() == typeid(T).hash_code();
33 }
34 template<typename T>
35 std::optional<T> value() const
36 {
37 // any_cast always checks this, to avoid an additional check we use exceptions
38 try {
39 return std::any_cast<T>(error);
40 } catch (const std::bad_any_cast &) {
41 return {};
42 }
43 }
44 template<typename T>
45 std::optional<T> takeValue()
46 {
47 // we can't use unchecked any_cast with moving because we can't access the error after a
48 // failed any_cast
49 if (error.type().hash_code() == typeid(T).hash_code()) {
50 auto value = std::any_cast<T>(std::move(error));
51 error = std::any();
52 return value;
53 }
54 return {};
55 }
56};
57
58namespace QXmpp {
59
60// defined here so that QXmppError is available
61
67template<typename T>
68const QXmppError &getError(const Result<T> &r) { return std::get<QXmppError>(r); }
69
75template<typename T>
76QXmppError &getError(Result<T> &r) { return std::get<QXmppError>(r); }
77
83template<typename T>
84QXmppError getError(Result<T> &&r) { return std::get<QXmppError>(std::move(r)); }
85
86} // namespace QXmpp
87
88#endif // QXMPPERROR_H
Definition Algorithms.h:14
std::variant< T, QXmppError > Result
Definition QXmppGlobal.h:209
const QXmppError & getError(const Result< T > &r)
Definition QXmppError.h:68
Definition QXmppError.h:17
std::any error
Definition QXmppError.h:19
QString description
Definition QXmppError.h:18
std::optional< T > takeValue()
Definition QXmppError.h:45
std::optional< T > value() const
Definition QXmppError.h:35
bool holdsType() const
Definition QXmppError.h:30