New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

error-ninja

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

error-ninja

Allows us to pre-define error types and error messages in each module.

  • 0.1.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
3
Maintainers
1
Weekly downloads
 
Created
Source

Error-Ninja

Error handling in Node can be a pain, it's tempting to just pass strings around so it's easier to handle, but using a proper Error object is a better way and Error Ninja can help with this.

What's the Point?

  1. Outputs a human-friendly error message in the terminal.
  2. Makes it easy to locate the source of errors in your code by assigning human-readable IDs to every error.
  3. Makes it easy for your frontend code to respond to errors without needing to understand the backend implementation.
  4. Allows you to decorate errors with extra properties which get printed to the terminal when the error gets thrown.
  5. Enables intelligent handling of errors using the extra properties added to the error e.g. if (err.id === 'XXX') {}.
  6. Errors from other modules or the Node.js core can be converted to ErrorNinja errors using ErrorNinja.convert().
  7. Can be used with Promises to quit the process in a .catch() block without causing any warnings.
  8. Behaves just like a traditional JavaScript Error - can be thrown and caught.
  9. Makes it easy to debug in development AND production.
  10. Allows you to detect if a variable is a JavaScript error or an ErrorNinja error.

Define Your Error Messages

First, at the top of a module define the dictionary of error IDs and error messages that will be available to that module.

const ErrorNinja = require('error-ninja').define({
	INVALID_BLOG_ID: 'The given blog ID does not exist!',
	ATTACHMENT_TOO_BIG: 'You cannot upload an attachment that big!',
	SOME_ERROR: 'Woah, this code is buggy!',
});

Create and Throw Errors

Now you can create an error. You can throw this error just like you would do normally.

const err = new ErrorNinja('INVALID_BLOG_ID');
throw err;

/*
	Outputs...
	Error [INVALID_BLOG_ID]: The given blog ID does not exist!
		 at new ErrorNinja (/path/to/Error-Ninja/errorNinja.js:36:19)
		 at Object.<anonymous> (/path/to/myScript.js:59:13)
		 at Module._compile (module.js:456:26)
		 at Object.Module._extensions..js (module.js:474:10)
		 at Module.load (module.js:356:32)
		 at Function.Module._load (module.js:312:12)
		 at Function.Module.runMain (module.js:497:10)
		 at startup (node.js:119:16)
		 at node.js:906:3
 */

Include Data in the Error

If you need to include some extra properties in the error you can pass a second parameter to the error constructor. By default this data will be output to the terminal if the error is thrown, and you'll also be able to access it when handling your error.

const err = new ErrorNinja('ATTACHMENT_TOO_BIG', { fileSize: 17483, maxSize: 1024, name: 'crash.log' });
console.log(err.data.fileSize);
throw err;

/*
	Outputs...
	Error [ATTACHMENT_TOO_BIG]: You cannot upload an attachment that big!
	----------
	{"fileSize":17483,"maxSize":1024,"name":"crash.log"}
	----------
		 at new ErrorNinja (/path/to/Error-Ninja/errorNinja.js:36:19)
		 at Object.<anonymous> (/path/to/myScript.js:59:13)
		 at Module._compile (module.js:456:26)
		 at Object.Module._extensions..js (module.js:474:10)
		 at Module.load (module.js:356:32)
		 at Function.Module._load (module.js:312:12)
		 at Function.Module.runMain (module.js:497:10)
		 at startup (node.js:119:16)
		 at node.js:906:3
 */

Turn Off Data Console Output

To prevent the extra error data being output in the terminal you can do one of two things:

  1. Pass false as the 3rd argument when creating an error:
const err = new ErrorNinja('SOME_ERROR', { abc: 'do-not-output-this' }, false);
  1. Or you can turn off data output for all errors created by this instance of Error Ninja by passing in a config option when defining your error dictionary.
const ErrorNinja = require('error-ninja').define({ ... }, { outputData: false });

Access Useful Properties in the Error

Apart from the usual error properties you can also access the following additional properties that should help with handling your errors.

const err = new ErrorNinja('ATTACHMENT_TOO_BIG', { fileSize: 17483, maxSize: 1024, name: 'crash.log' });

err.id;       // "ATTACHMENT_TOO_BIG"
err.isError;  // True
err.isNinja;  // True
err.human;    // "You cannot upload an attachment that big!"
err.data;     // (mixed) e.g. { fileSize: 17483, maxSize: 1024, name: 'crash.log' }
							// data defaults to {}

Convert an existing error to an ErrorNinja

You can convert ordinary errors created by the Node.js core or other modules to ErrorNinja errors without throwing them:

	doSomethingAsync((err, result) => {
		err = ErrorNinja.convert(err, 'MY_ERROR_ID'/* , data, outputData */);

		ErrorNinja.isNinja(err);  // true.
		throw err;
	});

You can also convert and throw them immediately:

doSomethingAsync((err, result) => {
	if (err) { ErrorNinja.throw(err, 'MY_ERROR_ID'/* , data, outputData */); }
});

Alternatively, you can convert the error and quit the Node.js process with a non-zero error code (which will be the ID of your error) without throwing it. The error and its stack trace will be printed to the terminal in the same way they would if you had thrown the error. This prevents Node.js from complaining when you need to output an error in a Promise .catch() block whilst terminating the process.

	doSomethingAsync()
		.then(result => {
			// Do something else here...
		})
		.catch(ErrorNinja.quit('MY_ERROR_ID'));  // Takes the "err" param passed to the .catch() block and converts it.

How to Tell if a Variable is an Error?

ErrorNinja provides two methods to detect if a variable is an error, or more specifically an ErrorNinja error.

	// Ordinary JavaScript errors.
	const err1 = new Error();
	ErrorNinja.isError(err1))  // true
	ErrorNinja.isNinja(err1))  // false

	// ErrorNinja errors.
	const err2 = new ErrorNinja('...');
	ErrorNinja.isError(err2))  // true
	ErrorNinja.isNinja(err2))  // true

Keywords

FAQs

Package last updated on 14 Feb 2017

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc