Skip to content

Commit bb4878d

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 569f51f commit bb4878d

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

quickjs.c

+17-2
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ typedef enum JSErrorEnum {
188188
JS_AGGREGATE_ERROR,
189189

190190
JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */
191+
JS_PLAIN_ERROR = JS_NATIVE_ERROR_COUNT
191192
} JSErrorEnum;
192193

193194
#define JS_MAX_LOCAL_VARS 65535
@@ -6601,8 +6602,11 @@ static JSValue JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num,
66016602
JSValue obj, ret, msg;
66026603

66036604
vsnprintf(buf, sizeof(buf), fmt, ap);
6604-
obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],
6605-
JS_CLASS_ERROR);
6605+
if (error_num == JS_PLAIN_ERROR)
6606+
obj = JS_NewError(ctx);
6607+
else
6608+
obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],
6609+
JS_CLASS_ERROR);
66066610
if (unlikely(JS_IsException(obj))) {
66076611
/* out of memory: throw JS_NULL to avoid recursing */
66086612
obj = JS_NULL;
@@ -6636,6 +6640,17 @@ static JSValue JS_ThrowError(JSContext *ctx, JSErrorEnum error_num,
66366640
return JS_ThrowError2(ctx, error_num, fmt, ap, add_backtrace);
66376641
}
66386642

6643+
JSValue __attribute__((format(printf, 2, 3))) JS_ThrowPlainError(JSContext *ctx, const char *fmt, ...)
6644+
{
6645+
JSValue val;
6646+
va_list ap;
6647+
6648+
va_start(ap, fmt);
6649+
val = JS_ThrowError(ctx, JS_PLAIN_ERROR, fmt, ap);
6650+
va_end(ap);
6651+
return val;
6652+
}
6653+
66396654
JSValue __attribute__((format(printf, 2, 3))) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...)
66406655
{
66416656
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)