Repository navigation
Expand file tree
/
Copy pathJsError.h
More file actions
78 lines (63 loc) · 2.72 KB
/
Copy pathJsError.h
File metadata and controls
78 lines (63 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef NATIVESCRIPT_COMMON_JS_ERROR_H_
#define NATIVESCRIPT_COMMON_JS_ERROR_H_
#include <v8.h>
#include <exception>
#include <memory>
#include <string>
namespace nativescript::common {
enum class JsErrorType {
kError,
kTypeError,
kRangeError,
kReferenceError,
kSyntaxError,
};
// A failure that JS observes as a thrown value. The core throws it in every
// build, never asserts on a path JS can reach, and converts it at the frame of
// each V8 callback it implements: a C++ exception must never unwind through V8
// frames.
//
// Construct, copy, catch and destroy it on the isolate's thread: the captured
// value is a v8::Global.
class JsError : public std::exception {
public:
// A new error object, built when the error reaches V8.
explicit JsError(std::string message, JsErrorType type = JsErrorType::kError);
// Rethrows `value` itself, so identity checks (===, instanceof) still hold
// where it lands. `message` describes it in logs.
static JsError FromValue(v8::Isolate* isolate, v8::Local<v8::Value> value,
std::string message);
// Throws what `tc` caught: Terminated when the isolate is terminating,
// otherwise a JsError carrying the caught value, its log message prefixed
// with `context`.
[[noreturn]] static void ThrowCaught(v8::Isolate* isolate,
const v8::TryCatch& tc,
const std::string& context);
const char* what() const noexcept override { return message_.c_str(); }
const std::string& message() const { return message_; }
// The value V8 should see: the captured one, or a new error object. Empty on
// a terminating isolate, which can't allocate one.
v8::Local<v8::Value> ToV8(v8::Isolate* isolate) const;
// Throws ToV8() into the isolate; does nothing on a terminating isolate.
void ThrowToV8(v8::Isolate* isolate) const;
private:
std::string message_;
JsErrorType type_ = JsErrorType::kError;
std::shared_ptr<v8::Global<v8::Value>> value_;
};
// Work cut short by isolate termination. It carries no captured V8 value.
// Each non-JS boundary decides what it means (nothing at a worker boundary,
// fatal at boot).
class Terminated : public std::exception {
public:
const char* what() const noexcept override {
return "interrupted by isolate termination";
}
// For a V8 callback that catches it. Termination is requested before V8
// starts unwinding, so JS can still be running: the callback must not
// return as if the work had finished. Throws an Error with what() while
// the isolate is not yet terminating; does nothing once it is.
void ThrowToV8(v8::Isolate* isolate) const;
};
} // namespace nativescript::common
#endif // NATIVESCRIPT_COMMON_JS_ERROR_H_