Add JS_ThrowPlainError

It's a helper for doing the following steps:

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

Fixes: https://github.com/quickjs-ng/quickjs/issues/375
This commit is contained in:
Saúl Ibarra Corretgé 2024-05-21 09:21:47 +02:00
parent 569f51fba2
commit bb4878dd50
2 changed files with 18 additions and 2 deletions

View file

@ -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
@ -6601,6 +6602,9 @@ static JSValue JS_ThrowError2(JSContext *ctx, JSErrorEnum error_num,
JSValue obj, ret, msg;
vsnprintf(buf, sizeof(buf), fmt, ap);
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))) {
@ -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;

View file

@ -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, ...);