|
| 1 | +#ifndef SRC_NODE_ERRORS_H_ |
| 2 | +#define SRC_NODE_ERRORS_H_ |
| 3 | + |
| 4 | +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS |
| 5 | + |
| 6 | +#include "node.h" |
| 7 | +#include "util-inl.h" |
| 8 | +#include "env-inl.h" |
| 9 | +#include "v8.h" |
| 10 | + |
| 11 | +namespace node { |
| 12 | + |
| 13 | +// Helpers to construct errors similar to the ones provided by |
| 14 | +// lib/internal/errors.js. |
| 15 | +// Example: with `V(ERR_INVALID_ARG_TYPE, TypeError)`, there will be |
| 16 | +// `node::ERR_INVALID_ARG_TYPE(isolate, "message")` returning |
| 17 | +// a `Local<Value>` containing the TypeError with proper code and message |
| 18 | + |
| 19 | +#define ERRORS_WITH_CODE(V) \ |
| 20 | + V(ERR_MEMORY_ALLOCATION_FAILED, Error) \ |
| 21 | + V(ERR_STRING_TOO_LARGE, Error) \ |
| 22 | + V(ERR_BUFFER_TOO_LARGE, Error) |
| 23 | + |
| 24 | +#define V(code, type) \ |
| 25 | + inline v8::Local<v8::Value> code(v8::Isolate* isolate, \ |
| 26 | + const char* message) { \ |
| 27 | + v8::Local<v8::String> js_code = OneByteString(isolate, #code); \ |
| 28 | + v8::Local<v8::String> js_msg = OneByteString(isolate, message); \ |
| 29 | + v8::Local<v8::Object> e = \ |
| 30 | + v8::Exception::type(js_msg)->ToObject( \ |
| 31 | + isolate->GetCurrentContext()).ToLocalChecked(); \ |
| 32 | + e->Set(isolate->GetCurrentContext(), OneByteString(isolate, "code"), \ |
| 33 | + js_code).FromJust(); \ |
| 34 | + return e; \ |
| 35 | + } |
| 36 | + ERRORS_WITH_CODE(V) |
| 37 | +#undef V |
| 38 | + |
| 39 | +// Errors with predefined static messages |
| 40 | + |
| 41 | +#define PREDEFINED_ERROR_MESSAGES(V) \ |
| 42 | + V(ERR_MEMORY_ALLOCATION_FAILED, "Failed to allocate memory") |
| 43 | + |
| 44 | +#define V(code, message) \ |
| 45 | + inline v8::Local<v8::Value> code(v8::Isolate* isolate) { \ |
| 46 | + return code(isolate, message); \ |
| 47 | + } |
| 48 | + PREDEFINED_ERROR_MESSAGES(V) |
| 49 | +#undef V |
| 50 | + |
| 51 | +// Errors with predefined non-static messages |
| 52 | + |
| 53 | +inline v8::Local<v8::Value> ERR_BUFFER_TOO_LARGE(v8::Isolate *isolate) { |
| 54 | + char message[128]; |
| 55 | + snprintf(message, sizeof(message), |
| 56 | + "Cannot create a Buffer larger than 0x%lx bytes", |
| 57 | + v8::TypedArray::kMaxLength); |
| 58 | + return ERR_BUFFER_TOO_LARGE(isolate, message); |
| 59 | +} |
| 60 | + |
| 61 | +inline v8::Local<v8::Value> ERR_STRING_TOO_LARGE(v8::Isolate *isolate) { |
| 62 | + char message[128]; |
| 63 | + snprintf(message, sizeof(message), |
| 64 | + "Cannot create a string larger than 0x%x bytes", |
| 65 | + v8::String::kMaxLength); |
| 66 | + return ERR_STRING_TOO_LARGE(isolate, message); |
| 67 | +} |
| 68 | + |
| 69 | +} // namespace node |
| 70 | + |
| 71 | +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS |
| 72 | + |
| 73 | +#endif // SRC_NODE_ERRORS_H_ |
0 commit comments