Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
pretty-error
Advanced tools
The pretty-error npm package is used to render error messages in a more visually appealing and readable format in Node.js applications. It transforms error stack traces into a more structured and stylized output, which can help developers to more easily identify the source and context of an error.
Customizing the appearance of errors
This feature allows developers to customize the appearance of the error output by appending styles to the default configuration.
const PrettyError = require('pretty-error');
const pe = new PrettyError();
pe.appendStyle({
'pretty-error > header > title > kind': {
display: 'none'
},
'pretty-error > header > colon': {
display: 'none'
}
});
console.log(pe.render(new Error('Something went wrong!')));
Start using pretty-error with default settings
This code sample demonstrates how to use pretty-error with its default settings to render a more readable error message.
const PrettyError = require('pretty-error');
const pe = new PrettyError();
console.log(pe.render(new Error('Something went wrong!')));
Skipping packages and paths in the stack trace
This feature allows developers to skip certain packages or paths when rendering the error stack trace, making it easier to focus on the relevant parts of the trace.
const PrettyError = require('pretty-error');
const pe = new PrettyError();
pe.skipPackage('express', 'mongoose');
pe.skipPath('/home/user/node_modules/');
console.log(pe.render(new Error('Something went wrong!')));
Chalk is a popular npm package that allows developers to style their terminal string output with colors and styles. While it doesn't format error messages specifically, it can be used in conjunction with other error handling to create a more readable output.
Signale is an npm package that provides a console logger with various log levels and customizable, pretty output. It includes features for timing functions, displaying badges, and more. It's similar to pretty-error in that it enhances the visual output of logs, but it's more focused on general logging rather than error stack traces.
CLI-Highlight is a syntax highlighter for the terminal. It can be used to highlight code snippets, including error stack traces, in various programming languages. It's similar to pretty-error in that it improves the readability of terminal output, but it's more generic and not specifically tailored to error messages.
A small tool to see node.js errors with less clutter:
... which is more readable compared to node's unformatted errors:
Install with npm:
$ npm install pretty-error
To see an error rendered with colors, you can do this:
var PrettyError = require('pretty-error');
var pe = new PrettyError();
var renderedError = pe.render(new Error('Some error message'));
console.log(renderedError);
Of course, you can render caught exceptions too:
try {
doSomethingThatThrowsAnError();
} catch (error) {
console.log(pe.render(error));
}
But if you want pretty-error to render all errors, there is a shortcut for it:
require('pretty-error').start();
... which is essentially equal to:
var PrettyError = require('pretty-error');
// instantiate PrettyError, which can then be used to render error objects
var pe = new PrettyError();
pe.start();
You can also preload pretty-error into your code using node's --require
argument:
$ node --require pretty-error/start your-module.js
PrettyError turns error objects into something similar to an html document, and then uses RenderKid to render the document using simple html/css-like commands. This allows PrettyError to be themed using simple css-like declarations.
PrettyError's default theme is a bunch of simple css-like rules. Here is the source of the default theme.
Since the default theme is all css, you can customize it to fit your taste. Let's do a minimal one:
// the start() shortcut returns an instance of PrettyError ...
pe = require('pretty-error').start();
// ... which we can then use to customize like this:
pe.appendStyle({
// this is a simple selector to the element that says 'Error'
'pretty-error > header > title > kind': {
// which we can hide:
display: 'none'
},
// the 'colon' after 'Error':
'pretty-error > header > colon': {
// we hide that too:
display: 'none'
},
// our error message
'pretty-error > header > message': {
// let's change its color:
color: 'bright-white',
// we can use black, red, green, yellow, blue, magenta, cyan, white,
// grey, bright-red, bright-green, bright-yellow, bright-blue,
// bright-magenta, bright-cyan, and bright-white
// we can also change the background color:
background: 'cyan',
// it understands paddings too!
padding: '0 1' // top/bottom left/right
},
// each trace item ...
'pretty-error > trace > item': {
// ... can have a margin ...
marginLeft: 2,
// ... and a bullet character!
bullet: '"<grey>o</grey>"'
// Notes on bullets:
//
// The string inside the quotation mark gets used as the character
// to show for the bullet point.
//
// You can set its color/background color using tags.
//
// This example sets the background color to white, and the text color
// to cyan, the character will be a hyphen with a space character
// on each side:
// example: '"<bg-white><cyan> - </cyan></bg-white>"'
//
// Note that we should use a margin of 3, since the bullet will be
// 3 characters long.
},
'pretty-error > trace > item > header > pointer > file': {
color: 'bright-cyan'
},
'pretty-error > trace > item > header > pointer > colon': {
color: 'cyan'
},
'pretty-error > trace > item > header > pointer > line': {
color: 'bright-cyan'
},
'pretty-error > trace > item > header > what': {
color: 'bright-white'
},
'pretty-error > trace > item > footer > addr': {
display: 'none'
}
});
This is how our minimal theme will look like:
Read RenderKid's docs to learn about all the css rules that are supported.
There are a few methods to help you customize the contents of your error logs.
Let's instantiate first:
PrettyError = require('pretty-error');
pe = new PrettyError();
// or:
pe = require('pretty-error').start();
You might want to substitute long paths with shorter, more readable aliases:
pe.alias('E:/open-source/theatrejs/lib', '(Theatre.js)');
You might want to skip trace lines that belong to specific packages (chai, when, socket.io):
pe.skipPackage('chai', 'when', 'socket.io');
// this will skip node.js, path.js, event.js, etc.
pe.skipNodeFiles();
pe.skipPath('/home/dir/someFile.js');
You can customize which trace lines get logged and which won't:
pe.skip(function(traceLine, lineNumber){
// if we know which package this trace line comes from, and it isn't
// our 'demo' package ...
if (typeof traceLine.packageName !== 'undefined' && traceLine.packageName !== 'demo') {
// then skip this line
return true;
}
// You can console.log(traceLine) to see all of it's properties.
// Don't expect all these properties to be present, and don't assume
// that our traceLine is always an object.
});
pe.filter(function(traceLine, lineNumber){
// the 'what' clause is something like:
// 'DynamicTimeline.module.exports.DynamicTimeline._verifyProp'
if (typeof traceLine.what !== 'undefined'){
// we can shorten it with a regex:
traceLine.what = traceLine.what.replace(
/(.*\.module\.exports\.)(.*)/, '$2'
);
}
});
pe.withoutColors(); // Errors will be rendered without coloring
PrettyError is very simple to set up, so it should be easy to use within other frameworks.
Most frameworks such as express, catch errors automatically and provide a mechanism to handle those errors. Here is an example of how you can use PrettyError to log unhandled errors in express:
// this is app.js
var express = require('express');
var PrettyError = require('pretty-error');
var app = express();
app.get('/', function(req, res) {
// this will throw an error:
var a = b;
});
var server = app.listen(3000, function(){
console.log('Server started \n');
});
// we can now instantiaite Prettyerror:
pe = new PrettyError();
// and use it for our app's error handler:
app.use(function(err, req, res, next){
console.log(pe.render(err));
next();
});
// we can optionally configure prettyError to simplify the stack trace:
pe.skipNodeFiles(); // this will skip events.js and http.js and similar core node files
pe.skipPackage('express'); // this will skip all the trace lines about express` core and sub-modules
PrettyError.start()
modifies the stack traces of all errors thrown anywhere in your code, so it could potentially break packages that rely on node's original stack traces. I've only encountered this problem once, and it was with BlueBird when Promise.longStackTraces()
was on.
In order to avoid this problem, it's better to not use PrettyError.start()
and instead, manually catch errors and render them with PrettyError:
var PrettyError = require('pretty-error');
var pe = new PrettyError();
// To render exceptions thrown in non-promies code:
process.on('uncaughtException', function(error){
console.log(pe.render(error));
});
// To render unhandled rejections created in BlueBird:
process.on('unhandledRejection', function(reason){
console.log("Unhandled rejection");
console.log(pe.render(reason));
});
// While PrettyError.start() works out of the box with when.js` unhandled rejections,
// now that wer'e manually rendering errors, we have to instead use npmjs.org/packages/pretty-monitor
// to handle when.js rejections.
The only drawback with this approach is that exceptions thrown in the first tick are not prettified. To fix that, you can delay your application's startup for one tick:
// (continued form above)
throw new Error(); // not prettified
process.nextTick(function(){
throw new Error(); // prettified
});
MIT
FAQs
See nodejs errors with less clutter
We found that pretty-error demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.