name: duk_safe_to_string
proto: |
const char *duk_safe_to_string(duk_context *ctx, duk_idx_t index);
stack: |
[ ... val! ... ] -> [ ... ToString(val)! ... ]
summary: |
Like duk_to_string()
but if
the initial string coercion fails, the error value is coerced to a string.
If that also fails, a fixed error string is returned.
The caller can safely use this function to coerce a value to a string,
which is useful in C code to print out a return value safely with
printf()
. The only uncaught errors possible are out-of-memory
and other internal errors which trigger fatal error handling anyway.
example: |
/* Coercion causes error. */
duk_eval_string(ctx, "({ toString: function () { throw new Error('toString error'); } })");
printf("coerced string: %s\n", duk_safe_to_string(ctx, -1)); /* -> "Error: toString error" */
duk_pop(ctx);
/* Coercion causes error, and the error itself cannot be string coerced. */
duk_eval_string(ctx, "({ toString: function () { var e = new Error('cannot string coerce me');"
" e.toString = function () { throw new Error('coercion error'); };"
" throw e; } })");
printf("coerced string: %s\n", duk_safe_to_string(ctx, -1)); /* -> "Error" */
duk_pop(ctx);
tags:
- stack
- string
- protected
seealso:
- duk_to_string
introduced: 1.0.0