Skip to content

Commit

Permalink
Add JS_ThrowPlainError
Browse files Browse the repository at this point in the history
It's a helper for doing the following steps:

- Building an Error object
- Attaching a formatted message
- Throwing the object

Fixes: #375
  • Loading branch information
saghul committed May 27, 2024
1 parent 569f51f commit bb4878d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
19 changes: 17 additions & 2 deletions quickjs.c
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ typedef enum JSErrorEnum {
JS_AGGREGATE_ERROR,

JS_NATIVE_ERROR_COUNT, /* number of different NativeError objects */
JS_PLAIN_ERROR = JS_NATIVE_ERROR_COUNT
} JSErrorEnum;

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

vsnprintf(buf, sizeof(buf), fmt, ap);
obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],
JS_CLASS_ERROR);
if (error_num == JS_PLAIN_ERROR)
obj = JS_NewError(ctx);
else
obj = JS_NewObjectProtoClass(ctx, ctx->native_error_proto[error_num],
JS_CLASS_ERROR);
if (unlikely(JS_IsException(obj))) {
/* out of memory: throw JS_NULL to avoid recursing */
obj = JS_NULL;
Expand Down Expand Up @@ -6636,6 +6640,17 @@ static JSValue JS_ThrowError(JSContext *ctx, JSErrorEnum error_num,
return JS_ThrowError2(ctx, error_num, fmt, ap, add_backtrace);
}

JSValue __attribute__((format(printf, 2, 3))) JS_ThrowPlainError(JSContext *ctx, const char *fmt, ...)
{
JSValue val;
va_list ap;

va_start(ap, fmt);
val = JS_ThrowError(ctx, JS_PLAIN_ERROR, fmt, ap);
va_end(ap);
return val;
}

JSValue __attribute__((format(printf, 2, 3))) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...)
{
JSValue val;
Expand Down
1 change: 1 addition & 0 deletions quickjs.h
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,7 @@ JS_EXTERN JSValue JS_GetException(JSContext *ctx);
JS_EXTERN JS_BOOL JS_IsError(JSContext *ctx, JSValue val);
JS_EXTERN void JS_ResetUncatchableError(JSContext *ctx);
JS_EXTERN JSValue JS_NewError(JSContext *ctx);
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowPlainError(JSContext *ctx, const char *fmt, ...);
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...);
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...);
JS_EXTERN JSValue __js_printf_like(2, 3) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...);
Expand Down

0 comments on commit bb4878d

Please sign in to comment.