You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

40 lines
1.4 KiB

name: duk_safe_to_string
proto: |
const char *duk_safe_to_string(duk_context *ctx, duk_idx_t index);
stack: |
[ ... val! ... ] -> [ ... ToString(val)! ... ]
summary: |
<p>Like <code><a href="#duk_to_string">duk_to_string()</a></code> 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.</p>
<p>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
<code>printf()</code>. The only uncaught errors possible are out-of-memory
and other internal errors which trigger fatal error handling anyway.</p>
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