Skip to content

Instantly share code, notes, and snippets.

@piyushchauhan2011
Forked from joyrexus/http-errors.js
Created April 4, 2021 23:48
Show Gist options
  • Select an option

  • Save piyushchauhan2011/c5060d07421e4365bcb0c61da4869189 to your computer and use it in GitHub Desktop.

Select an option

Save piyushchauhan2011/c5060d07421e4365bcb0c61da4869189 to your computer and use it in GitHub Desktop.
HTTP Error classes in Node.js
module.exports = CustomError;
function CustomError(message, extra) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
this.extra = extra;
}
require('util').inherits(CustomError, Error);

Sometimes you want to wrap error objects with application-specific errors for your stack traces.

This example also shows how to add an extra parameter called extra that will be stored as a property on the error.

Example usage:

var CustomError = require('./errors/custom-error');

function doSomethingRisky(callback) {
  throw new CustomError('You lost!', 42);
}
// Mini test suite for our custom error
var assert = require('assert');
var CustomError = require('./errors/custom-error');
function doSomethingBad() {
throw new CustomError('It went bad!', 42);
}
try {
doSomethingBad();
} catch (err) {
// The name property should be set to the error's name
assert(err.name = 'CustomError');
// The error should be an instance of its class
assert(err instanceof CustomError);
// The error should be an instance of builtin Error
assert(err instanceof Error);
// The error should be recognized by Node.js' util#isError
assert(require('util').isError(err));
// The error should have recorded a stack
assert(err.stack);
// toString should return the default error message formatting
assert.strictEqual(err.toString(),
'CustomError: It went bad!');
// The stack should start with the default error message formatting
assert.strictEqual(err.stack.split('\n')[0],
'CustomError: It went bad!');
// The first stack frame should be the function where the error was thrown.
assert.strictEqual(err.stack.split('\n')[1].indexOf('doSomethingBad'), 7);
// The extra property should have been set
assert.strictEqual(err.extra, 42);
}
// Spoiler: It passes!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment