Skip to content

Commit fd84161

Browse files
committed
Add JS_ThrowPlainError
It's a helper for doing the following steps: - Building an Error object - Attaching a formatted message - Throwing the object Fixes: #375
1 parent f588210 commit fd84161

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

quickjs.c

+37
Original file line numberDiff line numberDiff line change
@@ -6673,6 +6673,43 @@ static JSValue JS_ThrowError(JSContext *ctx, JSErrorEnum error_num,
66736673
return JS_ThrowError2(ctx, error_num, fmt, ap, add_backtrace);
66746674
}
66756675

6676+
JSValue __attribute__((format(printf, 2, 3))) JS_ThrowPlainError(JSContext *ctx, const char *fmt, ...)
6677+
{
6678+
JSRuntime *rt = ctx->rt;
6679+
JSStackFrame *sf;
6680+
BOOL add_backtrace;
6681+
JSValue val, ret;
6682+
char buf[256];
6683+
va_list ap;
6684+
6685+
sf = rt->current_stack_frame;
6686+
add_backtrace = !rt->in_out_of_memory &&
6687+
(!sf || (JS_GetFunctionBytecode(sf->cur_func) == NULL));
6688+
6689+
va_start(ap, fmt);
6690+
vsnprintf(buf, sizeof(buf), fmt, ap);
6691+
va_end(ap);
6692+
6693+
val = JS_NewError(ctx);
6694+
if (unlikely(JS_IsException(val))) {
6695+
/* out of memory: throw JS_NULL to avoid recursing */
6696+
val = JS_NULL;
6697+
} else {
6698+
JSValue msg = JS_NewString(ctx, buf);
6699+
if (JS_IsException(msg))
6700+
msg = JS_NewString(ctx, "Invalid error message");
6701+
if (!JS_IsException(msg)) {
6702+
JS_DefinePropertyValue(ctx, val, JS_ATOM_message, msg,
6703+
JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
6704+
}
6705+
}
6706+
if (add_backtrace) {
6707+
build_backtrace(ctx, val, NULL, 0, 0, 0);
6708+
}
6709+
ret = JS_Throw(ctx, val);
6710+
return ret;
6711+
}
6712+
66766713
JSValue __attribute__((format(printf, 2, 3))) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...)
66776714
{
66786715
JSValue val;

quickjs.h

+1
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,7 @@ JS_EXTERN JSValue JS_GetException(JSContext *ctx);
580580
JS_EXTERN JS_BOOL JS_IsError(JSContext *ctx, JSValue val);
581581
JS_EXTERN void JS_ResetUncatchableError(JSContext *ctx);
582582
JS_EXTERN JSValue JS_NewError(JSContext *ctx);
583+
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowPlainError(JSContext *ctx, const char *fmt, ...);
583584
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...);
584585
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...);
585586
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...);

0 commit comments

Comments
 (0)