QXmpp  Version: 1.10.4
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 
13 class QFileDevice;
14 class QIODevice;
15 class QNetworkReply;
16 
17 struct 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 (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 
58 #endif // QXMPPERROR_H
std::optional< T > value() const
Definition: QXmppError.h:35
Definition: QXmppError.h:17
bool holdsType() const
Definition: QXmppError.h:30
std::any error
Definition: QXmppError.h:19
std::optional< T > takeValue()
Definition: QXmppError.h:45
QString description
Definition: QXmppError.h:18