nx_metadata_sdk  1.0
Metadata SDK
result.h
1 // Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/
2 
3 #pragma once
4 
5 #include <nx/sdk/i_string.h>
6 
7 namespace nx::sdk {
8 
10 enum class ErrorCode: int
11 {
12  noError = 0,
13  networkError = -22,
14  unauthorized = -1,
15  internalError = -1000, //< Assertion-failure-like error.
16  invalidParams = -1001, //< Method arguments are invalid.
17  notImplemented = -21,
18  otherError = -100,
19 };
20 
21 class Error
22 {
23 public:
24  Error(ErrorCode errorCode, const IString* errorMessage):
25  m_errorCode(errorCode), m_errorMessage(errorMessage)
26  {
27  }
28 
29  bool isOk() const
30  {
31  return m_errorCode == ErrorCode::noError && m_errorMessage == nullptr;
32  }
33 
34  ErrorCode errorCode() const { return m_errorCode; }
35  const IString* errorMessage() const { return m_errorMessage; }
36 
37  Error(Error&&) = default;
38  Error& operator=(const Error&) = default;
39 
40 private:
41  ErrorCode m_errorCode;
42  const IString* m_errorMessage;
43 };
44 
45 template<typename Value>
46 class Result
47 {
48 public:
49  Result(): m_error(ErrorCode::noError, nullptr) {}
50 
51  Result(Value value): m_error(ErrorCode::noError, nullptr), m_value(std::move(value)) {}
52 
53  Result(Error&& error): m_error(std::move(error)) {}
54 
55  Result& operator=(Error&& error)
56  {
57  m_error = std::move(error);
58  m_value = Value{};
59  return *this;
60  }
61 
62  Result& operator=(Value value)
63  {
64  m_error = Error{ErrorCode::noError, nullptr};
65  m_value = value;
66  return *this;
67  }
68 
69  bool isOk() const { return m_error.isOk(); }
70 
71  const Error& error() const { return m_error; }
72  Value value() const { return m_value; }
73 
74 private:
75  Error m_error;
76  Value m_value{};
77 };
78 
79 template<>
80 class Result<void>
81 {
82 public:
83  Result(): m_error(ErrorCode::noError, nullptr) {}
84 
85  Result(Error&& error): m_error(std::move(error)) {}
86 
87  Result& operator=(Error&& error)
88  {
89  m_error = std::move(error);
90  return *this;
91  }
92 
93  bool isOk() const { return m_error.isOk(); }
94 
95  const Error& error() const { return m_error; }
96 
97 private:
98  Error m_error;
99 };
100 
101 } // namespace nx::sdk
Definition: i_string.h:9
Definition: result.h:46
Definition: device_agent.h:13
Definition: result.h:21