Introduction to Pretty-Error
Pretty-Error is a powerful, customizable error handling and debugging library for Node.js.
It aims to enhance the readability of error messages by formatting them in a clear and visually appealing manner.
Whether you are building a simple application or a complex system, Pretty-Error can help you quickly pinpoint issues
and debug them efficiently.
Installing Pretty-Error
You can install Pretty-Error via npm:
npm install pretty-error
Basic Usage
Below is an example demonstrating how to integrate Pretty-Error into your Node.js application.
const PrettyError = require('pretty-error'); const pe = new PrettyError();
try {
throw new Error('Something went wrong!');
} catch (err) {
console.log(pe.render(err));
}
Customizing Pretty-Error
Pretty-Error allows extensive customization options to tailor error messages to your needs.
Skipping Paths
You can skip specific paths from the error stack trace to declutter your error messages.
pe.skipPath('/node_modules/'); pe.skipPath('/internal/');
Skipping Packages
Certain packages can be skipped entirely from the stack trace.
pe.skipPackage('express'); pe.skipPackage('mocha');
Styles
Customize the style of error messages to highlight specific parts.
pe.appendStyle({
'pretty-error > header > title > kind': {
display: 'inline-block',
background: 'red',
color: 'white'
}
});
Complete Node.js Application with Pretty-Error
Here is a complete example of a Node.js application that uses various Pretty-Error features.
const PrettyError = require('pretty-error'); const express = require('express'); const app = express(); const pe = new PrettyError();
pe.skipPackage('express');
app.get('/', (req, res) => {
throw new Error('Root route error');
});
app.use((err, req, res, next) => {
console.error(pe.render(err));
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
In this example, we configured Pretty-Error to skip errors from the ‘express’ package and used it within an Express.js middleware.
Hash: 464af6b4ef2c5a5e3c2100a4a1e3f60f5555a32fb28306bd43b31370898d055f