BindingCallContext.h (2526B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 /** 8 * A struct that encapsulates a JSContex and information about 9 * which binding method was called. The idea is to automatically annotate 10 * exceptions thrown via the BindingCallContext with the method name. 11 */ 12 13 #ifndef mozilla_dom_BindingCallContext_h 14 #define mozilla_dom_BindingCallContext_h 15 16 #include <utility> 17 18 #include "js/TypeDecls.h" 19 #include "mozilla/Assertions.h" 20 #include "mozilla/Attributes.h" 21 #include "mozilla/ErrorResult.h" 22 23 namespace mozilla::dom { 24 25 class MOZ_NON_TEMPORARY_CLASS MOZ_STACK_CLASS BindingCallContext { 26 public: 27 // aCx is allowed to be null. If it is, the BindingCallContext should 28 // generally act like a null JSContext*: test false when tested as a boolean 29 // and produce nullptr when used as a JSContext*. 30 // 31 // aMethodDescription should be something with longer lifetime than this 32 // BindingCallContext. Most simply, a string literal. nullptr or "" is 33 // allowed if we want to not have any particular message description. This 34 // argument corresponds to the "context" string used for DOM error codes that 35 // support one. See Errors.msg and the documentation for 36 // ErrorResult::MaybeSetPendingException for details on he context arg. 37 BindingCallContext(JSContext* aCx, const char* aMethodDescription) 38 : mCx(aCx), mDescription(aMethodDescription) {} 39 40 ~BindingCallContext() = default; 41 42 // Allow passing a BindingCallContext as a JSContext*, as needed. 43 operator JSContext*() const { return mCx; } 44 45 // Allow testing a BindingCallContext for falsiness, just like a 46 // JSContext* could be tested. 47 explicit operator bool() const { return !!mCx; } 48 49 // Allow throwing an error message, if it has a context. 50 template <dom::ErrNum errorNumber, typename... Ts> 51 bool ThrowErrorMessage(Ts&&... aMessageArgs) const { 52 static_assert(ErrorFormatHasContext[errorNumber], 53 "We plan to add a context; it better be expected!"); 54 MOZ_ASSERT(mCx); 55 return dom::ThrowErrorMessage<errorNumber>( 56 mCx, mDescription, std::forward<Ts>(aMessageArgs)...); 57 } 58 59 private: 60 JSContext* const mCx; 61 const char* const mDescription; 62 }; 63 64 } // namespace mozilla::dom 65 66 #endif // mozilla_dom_BindingCallContext_h