Skip to content

Commit 4005ad6

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 4005ad6

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

quickjs.c

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ typedef enum JSErrorEnum {
193193
JS_AGGREGATE_ERROR,
194194

195195
JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */
196+
JS_PLAIN_ERROR = JS_NATIVE_ERROR_COUNT
196197
} JSErrorEnum;
197198

198199
#define JS_MAX_LOCAL_VARS 65535
@@ -6638,8 +6639,11 @@ static JSValue JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num,
66386639
JSValue obj, ret, msg;
66396640

66406641
vsnprintf(buf, sizeof(buf), fmt, ap);
6641-
obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],
6642-
JS_CLASS_ERROR);
6642+
if (error_num == JS_PLAIN_ERROR)
6643+
obj = JS_NewError(ctx);
6644+
else
6645+
obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],
6646+
JS_CLASS_ERROR);
66436647
if (unlikely(JS_IsException(obj))) {
66446648
/* out of memory: throw JS_NULL to avoid recursing */
66456649
obj = JS_NULL;
@@ -6673,6 +6677,17 @@ static JSValue JS_ThrowError(JSContext *ctx, JSErrorEnum error_num,
66736677
return JS_ThrowError2(ctx, error_num, fmt, ap, add_backtrace);
66746678
}
66756679

6680+
JSValue __attribute__((format(printf, 2, 3))) JS_ThrowPlainError(JSContext *ctx, const char *fmt, ...)
6681+
{
6682+
JSValue val;
6683+
va_list ap;
6684+
6685+
va_start(ap, fmt);
6686+
val = JS_ThrowError(ctx, JS_PLAIN_ERROR, fmt, ap);
6687+
va_end(ap);
6688+
return val;
6689+
}
6690+
66766691
JSValue __attribute__((format(printf, 2, 3))) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...)
66776692
{
66786693
JSValue val;

quickjs.h

Lines changed: 1 addition & 0 deletions
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)