blob: c87ce916501fac6b0de03a11b92d819693173ae9 [file] [log] [blame]
deadbeef6038e972017-02-16 23:31:33 -08001/*
2 * Copyright 2017 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef API_RTCERROR_H_
12#define API_RTCERROR_H_
deadbeef6038e972017-02-16 23:31:33 -080013
Jonas Olsson3e18c822018-04-18 10:11:07 +020014#ifdef UNIT_TEST
deadbeef6038e972017-02-16 23:31:33 -080015#include <ostream>
Jonas Olsson3e18c822018-04-18 10:11:07 +020016#endif // UNIT_TEST
deadbeef6038e972017-02-16 23:31:33 -080017#include <string>
18#include <utility> // For std::move.
19
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
21#include "rtc_base/logging.h"
deadbeef6038e972017-02-16 23:31:33 -080022
23namespace webrtc {
24
25// Enumeration to represent distinct classes of errors that an application
26// may wish to act upon differently. These roughly map to DOMExceptions or
27// RTCError "errorDetailEnum" values in the web API, as described in the
28// comments below.
29enum class RTCErrorType {
30 // No error.
31 NONE,
32
33 // An operation is valid, but currently unsupported.
34 // Maps to OperationError DOMException.
35 UNSUPPORTED_OPERATION,
36
37 // A supplied parameter is valid, but currently unsupported.
38 // Maps to OperationError DOMException.
39 UNSUPPORTED_PARAMETER,
40
41 // General error indicating that a supplied parameter is invalid.
42 // Maps to InvalidAccessError or TypeError DOMException depending on context.
43 INVALID_PARAMETER,
44
45 // Slightly more specific than INVALID_PARAMETER; a parameter's value was
46 // outside the allowed range.
47 // Maps to RangeError DOMException.
48 INVALID_RANGE,
49
50 // Slightly more specific than INVALID_PARAMETER; an error occurred while
51 // parsing string input.
52 // Maps to SyntaxError DOMException.
53 SYNTAX_ERROR,
54
55 // The object does not support this operation in its current state.
56 // Maps to InvalidStateError DOMException.
57 INVALID_STATE,
58
59 // An attempt was made to modify the object in an invalid way.
60 // Maps to InvalidModificationError DOMException.
61 INVALID_MODIFICATION,
62
63 // An error occurred within an underlying network protocol.
64 // Maps to NetworkError DOMException.
65 NETWORK_ERROR,
66
67 // Some resource has been exhausted; file handles, hardware resources, ports,
68 // etc.
69 // Maps to OperationError DOMException.
70 RESOURCE_EXHAUSTED,
71
72 // The operation failed due to an internal error.
73 // Maps to OperationError DOMException.
74 INTERNAL_ERROR,
75};
76
77// Roughly corresponds to RTCError in the web api. Holds an error type, a
78// message, and possibly additional information specific to that error.
79//
80// Doesn't contain anything beyond a type and message now, but will in the
81// future as more errors are implemented.
82class RTCError {
83 public:
84 // Constructors.
85
86 // Creates a "no error" error.
87 RTCError() {}
88 explicit RTCError(RTCErrorType type) : type_(type) {}
89 // For performance, prefer using the constructor that takes a const char* if
90 // the message is a static string.
91 RTCError(RTCErrorType type, const char* message)
92 : type_(type), static_message_(message), have_string_message_(false) {}
93 RTCError(RTCErrorType type, std::string&& message)
94 : type_(type), string_message_(message), have_string_message_(true) {}
95
96 // Delete the copy constructor and assignment operator; there aren't any use
97 // cases where you should need to copy an RTCError, as opposed to moving it.
98 // Can revisit this decision if use cases arise in the future.
99 RTCError(const RTCError& other) = delete;
100 RTCError& operator=(const RTCError& other) = delete;
101
102 // Move constructor and move-assignment operator.
103 RTCError(RTCError&& other);
104 RTCError& operator=(RTCError&& other);
105
106 ~RTCError();
107
108 // Identical to default constructed error.
109 //
110 // Preferred over the default constructor for code readability.
111 static RTCError OK();
112
113 // Error type.
114 RTCErrorType type() const { return type_; }
115 void set_type(RTCErrorType type) { type_ = type; }
116
117 // Human-readable message describing the error. Shouldn't be used for
118 // anything but logging/diagnostics, since messages are not guaranteed to be
119 // stable.
120 const char* message() const;
121 // For performance, prefer using the method that takes a const char* if the
122 // message is a static string.
123 void set_message(const char* message);
124 void set_message(std::string&& message);
125
126 // Convenience method for situations where you only care whether or not an
127 // error occurred.
128 bool ok() const { return type_ == RTCErrorType::NONE; }
129
130 private:
131 RTCErrorType type_ = RTCErrorType::NONE;
132 // For performance, we use static strings wherever possible. But in some
133 // cases the error string may need to be constructed, in which case an
134 // std::string is used.
135 union {
136 const char* static_message_ = "";
137 std::string string_message_;
138 };
139 // Whether or not |static_message_| or |string_message_| is being used in the
140 // above union.
141 bool have_string_message_ = false;
142};
143
144// Outputs the error as a friendly string. Update this method when adding a new
145// error type.
146//
147// Only intended to be used for logging/disagnostics.
Taylor Brandstetterbd739282018-04-20 15:58:11 +0000148std::string ToString(RTCErrorType error);
Jonas Olssond7ee7202018-04-18 10:11:07 +0200149
Jonas Olsson3e18c822018-04-18 10:11:07 +0200150#ifdef UNIT_TEST
151inline std::ostream& operator<<( // no-presubmit-check TODO(webrtc:8982)
152 std::ostream& stream, // no-presubmit-check TODO(webrtc:8982)
153 RTCErrorType error) {
154 return stream << ToString(error);
155}
156#endif // UNIT_TEST
157
deadbeef6038e972017-02-16 23:31:33 -0800158// Helper macro that can be used by implementations to create an error with a
159// message and log it. |message| should be a string literal or movable
160// std::string.
Jonas Olssonabbe8412018-04-03 13:40:05 +0200161#define LOG_AND_RETURN_ERROR_EX(type, message, severity) \
162 { \
163 RTC_DCHECK(type != RTCErrorType::NONE); \
164 RTC_LOG(severity) << message << " (" << ToString(type) << ")"; \
165 return webrtc::RTCError(type, message); \
deadbeef6038e972017-02-16 23:31:33 -0800166 }
167
168#define LOG_AND_RETURN_ERROR(type, message) \
169 LOG_AND_RETURN_ERROR_EX(type, message, LS_ERROR)
170
171// RTCErrorOr<T> is the union of an RTCError object and a T object. RTCErrorOr
172// models the concept of an object that is either a usable value, or an error
173// Status explaining why such a value is not present. To this end RTCErrorOr<T>
174// does not allow its RTCErrorType value to be RTCErrorType::NONE. This is
175// enforced by a debug check in most cases.
176//
177// The primary use-case for RTCErrorOr<T> is as the return value of a function
178// which may fail. For example, CreateRtpSender will fail if the parameters
179// could not be successfully applied at the media engine level, but if
180// successful will return a unique_ptr to an RtpSender.
181//
182// Example client usage for a RTCErrorOr<std::unique_ptr<T>>:
183//
184// RTCErrorOr<std::unique_ptr<Foo>> result = FooFactory::MakeNewFoo(arg);
185// if (result.ok()) {
186// std::unique_ptr<Foo> foo = result.ConsumeValue();
187// foo->DoSomethingCool();
188// } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100189// RTC_LOG(LS_ERROR) << result.error();
deadbeef6038e972017-02-16 23:31:33 -0800190// }
191//
192// Example factory implementation returning RTCErrorOr<std::unique_ptr<T>>:
193//
194// RTCErrorOr<std::unique_ptr<Foo>> FooFactory::MakeNewFoo(int arg) {
195// if (arg <= 0) {
196// return RTCError(RTCErrorType::INVALID_RANGE, "Arg must be positive");
197// } else {
198// return std::unique_ptr<Foo>(new Foo(arg));
199// }
200// }
201//
202template <typename T>
203class RTCErrorOr {
204 // Used to convert between RTCErrorOr<Foo>/RtcErrorOr<Bar>, when an implicit
205 // conversion from Foo to Bar exists.
206 template <typename U>
207 friend class RTCErrorOr;
208
209 public:
210 typedef T element_type;
211
212 // Constructs a new RTCErrorOr with RTCErrorType::INTERNAL_ERROR error. This
213 // is marked 'explicit' to try to catch cases like 'return {};', where people
214 // think RTCErrorOr<std::vector<int>> will be initialized with an empty
215 // vector, instead of a RTCErrorType::INTERNAL_ERROR error.
oprypin8e58d652017-03-21 07:52:41 -0700216 RTCErrorOr() : error_(RTCErrorType::INTERNAL_ERROR) {}
deadbeef6038e972017-02-16 23:31:33 -0800217
218 // Constructs a new RTCErrorOr with the given non-ok error. After calling
219 // this constructor, calls to value() will DCHECK-fail.
220 //
221 // NOTE: Not explicit - we want to use RTCErrorOr<T> as a return
222 // value, so it is convenient and sensible to be able to do 'return
223 // RTCError(...)' when the return type is RTCErrorOr<T>.
224 //
225 // REQUIRES: !error.ok(). This requirement is DCHECKed.
oprypin8e58d652017-03-21 07:52:41 -0700226 RTCErrorOr(RTCError&& error) : error_(std::move(error)) { // NOLINT
deadbeef6038e972017-02-16 23:31:33 -0800227 RTC_DCHECK(!error.ok());
228 }
229
230 // Constructs a new RTCErrorOr with the given value. After calling this
231 // constructor, calls to value() will succeed, and calls to error() will
232 // return a default-constructed RTCError.
233 //
234 // NOTE: Not explicit - we want to use RTCErrorOr<T> as a return type
235 // so it is convenient and sensible to be able to do 'return T()'
236 // when the return type is RTCErrorOr<T>.
oprypin8e58d652017-03-21 07:52:41 -0700237 RTCErrorOr(T&& value) : value_(std::move(value)) {} // NOLINT
deadbeef6038e972017-02-16 23:31:33 -0800238
239 // Delete the copy constructor and assignment operator; there aren't any use
240 // cases where you should need to copy an RTCErrorOr, as opposed to moving
241 // it. Can revisit this decision if use cases arise in the future.
242 RTCErrorOr(const RTCErrorOr& other) = delete;
243 RTCErrorOr& operator=(const RTCErrorOr& other) = delete;
244
245 // Move constructor and move-assignment operator.
deadbeefb5388d72017-02-24 01:17:43 -0800246 //
247 // Visual Studio doesn't support "= default" with move constructors or
248 // assignment operators (even though they compile, they segfault), so define
249 // them explicitly.
250 RTCErrorOr(RTCErrorOr&& other)
251 : error_(std::move(other.error_)), value_(std::move(other.value_)) {}
252 RTCErrorOr& operator=(RTCErrorOr&& other) {
253 error_ = std::move(other.error_);
254 value_ = std::move(other.value_);
255 return *this;
256 }
deadbeef6038e972017-02-16 23:31:33 -0800257
258 // Conversion constructor and assignment operator; T must be copy or move
259 // constructible from U.
260 template <typename U>
oprypin8e58d652017-03-21 07:52:41 -0700261 RTCErrorOr(RTCErrorOr<U> other) // NOLINT
deadbeef6038e972017-02-16 23:31:33 -0800262 : error_(std::move(other.error_)), value_(std::move(other.value_)) {}
263 template <typename U>
264 RTCErrorOr& operator=(RTCErrorOr<U> other) {
265 error_ = std::move(other.error_);
266 value_ = std::move(other.value_);
267 return *this;
268 }
269
270 // Returns a reference to our error. If this contains a T, then returns
271 // default-constructed RTCError.
272 const RTCError& error() const { return error_; }
273
274 // Moves the error. Can be useful if, say "CreateFoo" returns an
275 // RTCErrorOr<Foo>, and internally calls "CreateBar" which returns an
276 // RTCErrorOr<Bar>, and wants to forward the error up the stack.
277 RTCError MoveError() { return std::move(error_); }
278
279 // Returns this->error().ok()
280 bool ok() const { return error_.ok(); }
281
282 // Returns a reference to our current value, or DCHECK-fails if !this->ok().
283 //
284 // Can be convenient for the implementation; for example, a method may want
285 // to access the value in some way before returning it to the next method on
286 // the stack.
287 const T& value() const {
288 RTC_DCHECK(ok());
289 return value_;
290 }
291 T& value() {
292 RTC_DCHECK(ok());
293 return value_;
294 }
295
296 // Moves our current value out of this object and returns it, or DCHECK-fails
297 // if !this->ok().
298 T MoveValue() {
299 RTC_DCHECK(ok());
300 return std::move(value_);
301 }
302
303 private:
304 RTCError error_;
305 T value_;
306};
307
308} // namespace webrtc
309
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200310#endif // API_RTCERROR_H_