Skip to content

Commit dc5d011

Browse files
committed
util.js - improve output for instances of Error
1 parent aeba6ce commit dc5d011

File tree

1 file changed

+35
-6
lines changed
  • python/pythonmonkey/builtin_modules

1 file changed

+35
-6
lines changed

python/pythonmonkey/builtin_modules/util.js

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,13 @@ const inspectDefaultOptions = Object.seal({
115115
const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
116116
const regExpToString = RegExp.prototype.toString;
117117
const dateToISOString = Date.prototype.toISOString;
118-
const errorToString = Error.prototype.toString;
118+
119+
/** Return String(val) surrounded by appropriate ANSI escape codes to change the console text colour. */
120+
function colour(colourCode, val)
121+
{
122+
const esc=String.fromCharCode(27);
123+
return `${esc}[${colourCode}m${val}${esc}[0m`
124+
}
119125

120126
var CIRCULAR_ERROR_MESSAGE;
121127

@@ -357,7 +363,8 @@ inspect.styles = Object.assign(Object.create(null), {
357363
'symbol': 'green',
358364
'date': 'magenta',
359365
// "name": intentionally not styling
360-
'regexp': 'red'
366+
'regexp': 'red',
367+
'error2': 'grey',
361368
});
362369

363370
function stylizeWithColor(str, styleType) {
@@ -524,8 +531,8 @@ function formatValue(ctx, value, recurseTimes, ln) {
524531
} else if (isError(value)) {
525532
// Make error with message first say the error
526533
if (keyLength === 0)
527-
return formatError(value);
528-
base = ` ${formatError(value)}`;
534+
return formatError(ctx, value);
535+
base = ` ${formatError(ctx, value)}`;
529536
} else if (isAnyArrayBuffer(value)) {
530537
// Fast path for ArrayBuffer and SharedArrayBuffer.
531538
// Can't do the same for DataView because it has a non-primitive
@@ -620,8 +627,30 @@ function formatPrimitive(fn, value) {
620627
return fn(value.toString(), 'symbol');
621628
}
622629

623-
function formatError(value) {
624-
return `[${errorToString.call(value)}]`;
630+
/**
631+
* Format an instance of Error. Error is the only type which is typically displayed using two different
632+
* colours -- the stack gets darker at the bottom where it's less relevant.
633+
*
634+
* @param ctx {object} inspect context - lets us know if we're using colors or not
635+
* @param error {object} instance of Error to inspect
636+
*/
637+
function formatError(ctx, error)
638+
{
639+
function style(str)
640+
{
641+
if (!ctx.stylize)
642+
return str;
643+
return ctx.stylize(str, 'error2');
644+
}
645+
646+
const stackEls = error.stack
647+
.split('\n')
648+
.filter(a => a.length > 0)
649+
.map(a => ` ${a}`);
650+
return (`${error.name}: ${error.message}\n`
651+
+ stackEls[0] + '\n'
652+
+ style(stackEls.slice(1).join('\n'))
653+
);
625654
}
626655

627656
function formatObject(ctx, value, recurseTimes, keys) {

0 commit comments

Comments
 (0)