Custom error nodejs

Future Studio provides on-demand learning & wants you to become a better Android (Retrofit, Gson, Glide, Picasso) and Node.js/hapi developer!

Handling errors plays a major role in your application. In error situations, you want to know the details of the issue and how to solve it. When developing your app, you can create your own errors.

Errors in Node.js are extensible classes. This tutorial walks you through the creation of your own error class.

Node.js Series Overview

  • Node.js
  • Strings
  • Streams
  • Date & Time
  • Arrays
  • Promises
  • JSON
  • Iterators
  • Classes
  • Numbers
  • Objects
  • File System
  • Map
  • Process
  • Symbols
  • Platform/OS
  • HTTPS
  • Hashing
  1. Increase the Memory Limit for Your Process

  2. Why You Should Add “node” in Your Travis Config

  3. Create a PDF from HTML with Puppeteer and Handlebars

  4. Create Your Own Custom Error

  5. Retrieve a Request’s IP Address in Node.js

  6. Detect the Node.js Version in a Running Process or App

  7. How to Base64 Encode/Decode a Value in Node.js

  8. Check if a Value Is Null or Undefined in JavaScript or Node.js

  9. How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”

  10. Fix „Socket Hang Up“ Errors

  11. Nested Destructuring in JavaScript or Node.js


  1. Increase the Memory Limit for Your Process


  2. Why You Should Add “node” in Your Travis Config

  3. Create a PDF from HTML with Puppeteer and Handlebars

  4. Create Your Own Custom Error
  5. Retrieve a Request’s IP Address in Node.js

  6. Detect the Node.js Version in a Running Process or App

  7. How to Base64 Encode/Decode a Value in Node.js

  8. Check if a Value Is Null or Undefined in JavaScript or Node.js

  9. How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”

  10. Fix „Socket Hang Up“ Errors

  11. Nested Destructuring in JavaScript or Node.js

  1. String Replace All Appearances

  2. Remove All Whitespace From a String in JavaScript

  3. Generate a Random ID or String in Node.js or JavaScript

  4. Remove Extra Spaces From a String in JavaScript or Node.js

  5. Remove Numbers From a String in JavaScript or Node.js

  6. Get the Part Before a Character in a String in JavaScript or Node.js

  7. Get the Part After a Character in a String in JavaScript or Node.js

  8. How to Check if a Value is a String in JavaScript or Node.js

  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript

  10. Check if a Value is a String in JavaScript and Node.js

  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js

  12. Split a String into a List of Characters in JavaScript and Node.js

  13. How to Generage a UUID in Node.js

  14. Reverse a String in JavaScript or Node.js

  15. Split a String into a List of Lines in JavaScript or Node.js

  16. Split a String into a List of Words in JavaScript or Node.js

  17. Detect if a String is in camelCase Format in Javascript or Node.js

  18. Check If a String Is in Lowercase in JavaScript or Node.js

  19. Check If a String is in Uppercase in JavaScript or Node.js

  20. Get the Part After First Occurrence in a String in JavaScript or Node.js

  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js

  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js

  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js

  24. How to Count Words in a File

  25. How to Shuffle the Characters of a String in JavaScript or Node.js

  26. Append Characters or Words to a String in JavaScript or Node.js


    (Coming soon)

  27. Check if a String is Empty in JavaScript or Node.js


    (Coming soon)

  28. Ensure a String Ends with a Given Character in JavaScript or Node.js


    (Coming soon)

  29. Left-Trim Characters Off a String in JavaScript or Node.js


    (Coming soon)

  30. Right-Trim Characters Off a String in JavaScript or Node.js


    (Coming soon)

  31. Lowercase the First Character of a String in JavaScript or Node.js


    (Coming soon)

  32. Uppercase the First Character of a String in JavaScript or Node.js


    (Coming soon)

  33. Prepend Characters or Words to a String in JavaScript or Node.js


    (Coming soon)

  1. String Replace All Appearances

  2. Remove All Whitespace From a String in JavaScript

  3. Generate a Random ID or String in Node.js or JavaScript

  4. Remove Extra Spaces From a String in JavaScript or Node.js

  5. Remove Numbers From a String in JavaScript or Node.js

  6. Get the Part Before a Character in a String in JavaScript or Node.js

  7. Get the Part After a Character in a String in JavaScript or Node.js

  8. How to Check if a Value is a String in JavaScript or Node.js

  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript

  10. Check if a Value is a String in JavaScript and Node.js

  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js

  12. Split a String into a List of Characters in JavaScript and Node.js

  13. How to Generage a UUID in Node.js

  14. Reverse a String in JavaScript or Node.js

  15. Split a String into a List of Lines in JavaScript or Node.js

  16. Split a String into a List of Words in JavaScript or Node.js

  17. Detect if a String is in camelCase Format in Javascript or Node.js

  18. Check If a String Is in Lowercase in JavaScript or Node.js

  19. Check If a String is in Uppercase in JavaScript or Node.js

  20. Get the Part After First Occurrence in a String in JavaScript or Node.js

  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js

  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js

  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js

  24. How to Count Words in a File

  25. How to Shuffle the Characters of a String in JavaScript or Node.js

  26. Append Characters or Words to a String in JavaScript or Node.js

    (Coming soon)
  27. Check if a String is Empty in JavaScript or Node.js

    (Coming soon)
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js

    (Coming soon)
  29. Left-Trim Characters Off a String in JavaScript or Node.js

    (Coming soon)
  30. Right-Trim Characters Off a String in JavaScript or Node.js

    (Coming soon)
  31. Lowercase the First Character of a String in JavaScript or Node.js

    (Coming soon)
  32. Uppercase the First Character of a String in JavaScript or Node.js

    (Coming soon)
  33. Prepend Characters or Words to a String in JavaScript or Node.js

    (Coming soon)

  1. Filter Data in Streams

  1. Get Number of Seconds Since Epoch in JavaScript

  2. Get Tomorrow’s Date in JavaScript

  3. Increase a Date in JavaScript by One Week

  4. Add Seconds to a Date in Node.js and JavaScript

  5. Add Month(s) to a Date in JavaScript or Node.js

  6. Add Week(s) to a Date in JavaScript or Node.js

  7. Get the Current Year in JavaScript or Node.js

  8. How to Get a UNIX Timestamp in JavaScript or Node.js

  9. How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js

  10. Add Days to a Date in JavaScript or Node.js

  11. Get Yesterday’s Date in JavaScript or Node.js

  12. Add Minutes to a Date in JavaScript or Node.js

  13. Add Hours to a Date in JavaScript or Node.js

  14. Check If a Date Is Today in JavaScript or Node.js

  15. Check If a Date is Tomorrow in JavaScript or Node.js

  16. Check If a Date is Yesterday in JavaScript or Node.js

  17. How to Format a Date YYYY-MM-DD in JavaScript or Node.js

  1. Get Number of Seconds Since Epoch in JavaScript

  2. Get Tomorrow’s Date in JavaScript

  3. Increase a Date in JavaScript by One Week

  4. Add Seconds to a Date in Node.js and JavaScript

  5. Add Month(s) to a Date in JavaScript or Node.js

  6. Add Week(s) to a Date in JavaScript or Node.js

  7. Get the Current Year in JavaScript or Node.js

  8. How to Get a UNIX Timestamp in JavaScript or Node.js

  9. How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js

  10. Add Days to a Date in JavaScript or Node.js

  11. Get Yesterday’s Date in JavaScript or Node.js

  12. Add Minutes to a Date in JavaScript or Node.js

  13. Add Hours to a Date in JavaScript or Node.js

  14. Check If a Date Is Today in JavaScript or Node.js

  15. Check If a Date is Tomorrow in JavaScript or Node.js

  16. Check If a Date is Yesterday in JavaScript or Node.js

  17. How to Format a Date YYYY-MM-DD in JavaScript or Node.js

  1. How to Run an Asynchronous Function in Array.map()

  2. How to Reset and Empty an Array

  3. Clone/Copy an Array in JavaScript and Node.js

  4. Get an Array With Unique Values (Delete Duplicates)

  5. Sort an Array of Integers in JavaScript and Node.js

  6. Sort a Boolean Array in JavaScript, TypeScript, or Node.js

  7. Check If an Array Contains a Given Value in JavaScript or Node.js

  8. Add an Item to the Beginning of an Array in JavaScript or Node.js

  9. Append an Item at the End of an Array in JavaScript or Node.js

  10. How to Exit and Stop a for Loop in JavaScript and Node.js

  11. Split an Array Into Smaller Array Chunks in JavaScript and Node.js

  12. How to Get an Index in a for…of Loop in JavaScript and Node.js

  13. How to Exit, Stop, or Break an Array#forEach Loop in JavaScript or Node.js

  14. Retrieve a Random Item From an Array in JavaScript or Node.js

  15. How to Reverse an Array in JavaScript and Node.js

  16. Sort an Array of Strings in JavaScript, TypeScript or Node.js

  17. Sort an Array of Objects in JavaScript, TypeScript or Node.js

  18. Check If a Value Is an Array in JavaScript or Node.js

  19. Join an Array of Strings to a Single String Value


    (Coming soon)


  1. How to Run an Asynchronous Function in Array.map()

  2. How to Reset and Empty an Array

  3. for…of vs. for…in Loops

  4. Clone/Copy an Array in JavaScript and Node.js

  5. Get an Array With Unique Values (Delete Duplicates)

  6. Sort an Array of Integers in JavaScript and Node.js

  7. Sort a Boolean Array in JavaScript, TypeScript, or Node.js

  8. Check If an Array Contains a Given Value in JavaScript or Node.js

  9. Add an Item to the Beginning of an Array in JavaScript or Node.js

  10. Append an Item at the End of an Array in JavaScript or Node.js

  11. How to Exit and Stop a for Loop in JavaScript and Node.js

  12. Split an Array Into Smaller Array Chunks in JavaScript and Node.js

  13. How to Get an Index in a for…of Loop in JavaScript and Node.js

  14. How to Exit, Stop, or Break an Array#forEach Loop in JavaScript or Node.js

  15. Retrieve a Random Item From an Array in JavaScript or Node.js

  16. How to Reverse an Array in JavaScript and Node.js

  17. Sort an Array of Strings in JavaScript, TypeScript or Node.js

  18. Sort an Array of Objects in JavaScript, TypeScript or Node.js

  19. Check If a Value Is an Array in JavaScript or Node.js

  20. Join an Array of Strings to a Single String Value

    (Coming soon)

  1. Callback and Promise Support in your Node.js Modules

  2. Run Async Functions/Promises in Sequence

  3. Run Async Functions/Promises in Parallel

  4. Run Async Functions in Batches

  5. How to Fix “Promise resolver undefined is not a function” in Node.js or JavaScript

  6. Detect if Value Is a Promise in Node.js and JavaScript

  7. Overview of Promise-Based APIs in Node.js


  1. Callback and Promise Support in your Node.js Modules

  2. Run Async Functions/Promises in Sequence

  3. Run Async Functions/Promises in Parallel

  4. Run Async Functions in Batches

  5. How to Fix “Promise resolver undefined is not a function” in Node.js or JavaScript

  6. Detect if Value Is a Promise in Node.js and JavaScript

  7. Overview of Promise-Based APIs in Node.js

  1. Human-Readable JSON.stringify() With Spaces and Line Breaks

  2. Write a JSON Object to a File

  3. Create a Custom “toJSON” Function in Node.js and JavaScript

  1. Human-Readable JSON.stringify() With Spaces and Line Breaks

  2. Write a JSON Object to a File

  3. Create a Custom “toJSON” Function in Node.js and JavaScript

  4. Securely Parse JSON

  1. Check If a Value Is Iterable in JavaScript or Node.js

  1. Check If a Value Is Iterable in JavaScript or Node.js

  1. Extend Multiple Classes (Multi Inheritance)

  2. Retrieve the Class Name at Runtime in JavaScript and Node.js

  1. Extend Multiple Classes (Multi Inheritance)

  2. Retrieve the Class Name at Runtime in JavaScript and Node.js

  1. Generate a Random Number in Range With JavaScript/Node.js

  2. Ensure a Positive Number in JavaScript or Node.js

  3. Check if a Number Is Infinity

  4. Check If a Number has Decimal Places in JavaScript or Node.js


    (Coming soon)

  5. Use Numeric Separators for Better Readability

  1. Generate a Random Number in Range With JavaScript/Node.js

  2. Ensure a Positive Number in JavaScript or Node.js

  3. Check if a Number Is Infinity

  4. Check If a Number has Decimal Places in JavaScript or Node.js

    (Coming soon)
  5. Use Numeric Separators for Better Readability

  1. How to Check if an Object is Empty in JavaScript or Node.js

  2. How to CamelCase Keys of an Object in JavaScript or Node.js

  3. How to Snake_Case Keys of an Object in JavaScript or Node.js

  4. How to Destructure a Dynamic Key in JavaScript or Node.js

  5. How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js

  6. How to Delete a Key From an Object in JavaScript or Node.js

  7. Iterate Through an Object’s Keys and Values in JavaScript or Node.js

  8. How to Convert URLSearchParams to Object

  9. Check If a Value Is an Object in JavaScript or Node.js

  10. Conditionally Add Properties to an Object in JavaScript or Node.js

  1. How to Merge Objects

  2. How to Check if an Object is Empty in JavaScript or Node.js

  3. How to CamelCase Keys of an Object in JavaScript or Node.js

  4. How to Snake_Case Keys of an Object in JavaScript or Node.js

  5. How to Destructure a Dynamic Key in JavaScript or Node.js

  6. How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js

  7. How to Delete a Key From an Object in JavaScript or Node.js

  8. Iterate Through an Object’s Keys and Values in JavaScript or Node.js

  9. How to Convert URLSearchParams to Object

  10. Check If a Value Is an Object in JavaScript or Node.js

  11. Conditionally Add Properties to an Object in JavaScript or Node.js

  1. Get a File’s Created Date

  2. Get a File’s Last Modified or Updated Date of a File

  3. How to Create an Empty File

  4. Check If a Path or File Exists

  5. Check If a Path Is a Directory

  6. Check If a Path Is a File

  7. Retrieve the Path to the User’s Home Directory

  8. Read File Content as String

  9. Check If a Directory Is Empty

  10. How to Create a Directory (and Parents If Needed)

  11. Get a File Name (With or Without Extension)

  1. Get a File’s Created Date

  2. Get a File’s Last Modified or Updated Date of a File

  3. How to Create an Empty File

  4. Check If a Path or File Exists

  5. How to Rename a File

  6. Check If a Path Is a Directory

  7. Check If a Path Is a File

  8. Retrieve the Path to the User’s Home Directory

  9. How to Touch a File

  10. Read File Content as String

  11. Check If a Directory Is Empty

  12. How to Create a Directory (and Parents If Needed)

  13. Get a File‘s Extension

  14. Get the Size of a File

  15. Get a File Name (With or Without Extension)

  16. Read a JSON File

  1. Create From Object

  2. Transform to an Object

  1. Determine the Node.js Version Running Your Script

  1. Determine the Node.js Version Running Your Script

  1. Check if a Value is a Symbol in JavaScript or Node.js

  1. Check if a Value is a Symbol in JavaScript or Node.js

  1. Detect if Running on Linux

  2. Detect if Running on macOS

  3. Detect if Running on Windows

  4. Check if Running on 64bit or 32bit Platform

  5. Constant for Platform-Specific Newline

  1. Detect if Running on Linux

  2. Detect if Running on macOS

  3. Detect if Running on Windows

  4. Check if Running on 64bit or 32bit Platform

  5. Constant for Platform-Specific Newline

  1. How to Download a File

  1. Retrieve the List of Supported Hash Algorithms

  1. Calculate an MD5 Hash

  2. Retrieve the List of Supported Hash Algorithms

  3. Calculate a SHA256 Hash

Create an Error Class

Node.js comes with an Error class. This error class gives you the core functionality of errors, like capturing a stack trace and assigning context data.

You can extend Node’s error class to create your own errors. Here’s an example of a NotEnoughCoffee error:

not-enough-coffee-error.js

class NotEnoughCoffee extends Error {  
  constructor (message) {
    super(message)

    // assign the error class name in your custom error (as a shortcut)
    this.name = this.constructor.name

    // capturing the stack trace keeps the reference to your error class
    Error.captureStackTrace(this, this.constructor);

    // you may also assign additional properties to your error
    this.isSleepy = true
  }
}

module.exports = NotEnoughCoffee  

The custom error extends the default Node.js error class. Setting the this.name property to the constructor’s name will reference NotEnoughCoffee in stack traces instead of the generic Error name.

Go ahead and add other class properties when needed. You can even add methods that are more helpful. Here’s an example:

class CoffeeNotFound extends Error {  
  constructor (message) {
    super(message)
    Error.captureStackTrace(this, this.constructor);

    this.name = this.constructor.name
    this.status = 404
  }

  statusCode() {
    return this.status
  }
}

module.exports = CoffeeNotFound  

This CoffeeNotFound error could be an HTTP error. You may intercept the response and map the error’s status to the HTTP response status.

Throwing Errors

Import the custom error in your app and use it when necessary. Here’s a simple example that just throws the NotEnoughCoffee error:

'use strict'

const NotEnoughCoffee = require('./error')

throw new NotEnoughCoffee('Well, you may need another coffee :)')  

The related error output on your terminal looks like this:

Stack trace when throwing the NotEnoughCoffee error

Custom errors are a good way to help your coworkers and other developers to know what’s wrong with the app configuration.

Enjoy coding & make it rock!

Here’s how you could create custom error classes in Node.js using latest ES6 / ES2015 syntax.

I’ve tried to make it as lean and unobtrusive as possible.

Defining our own base class for errors

errors/AppError.js

module.exports = class AppError extends Error {
  constructor (message, status) {
  
    // Calling parent constructor of base Error class.
    super(message);
    
    // Saving class name in the property of our custom error as a shortcut.
    this.name = this.constructor.name;

    // Capturing stack trace, excluding constructor call from it
    // (this is probably no longer required in node >=8, see the comments)
    Error.captureStackTrace(this, this.constructor);
    
    // You can use any additional properties you want.
    // I'm going to use preferred HTTP status for this error types.
    // `500` is the default value if not specified.
    this.status = status || 500;
    
  }
};

Defining specific error types

errors/EmailTakenError.js

module.exports = class EmailTakenError extends require('./errors/AppError') {
  constructor (message) {
    // Providing default message and overriding status code.
    super(message || 'Specified E-Mail is already taken', 400);
  }
};

errors/RequestValidationError.js

module.exports = class extends require('./AppError') {
  constructor (fields) {
    // Overriding both message and status code.
    super('Request validation failed', 400);
    // Saving custom property.
    this.fields = fields || {};
  }
};

Throwing and catching

const AppError = require('./../api/errors/AppError');
const EmailTakenError = require('./../api/errors/EmailTakenError');
const RequestValidationError = require('./../api/errors/RequestValidationError');


try {
  // Throwing EmailTakenError exception.
  throw new EmailTakenError();
} catch (error) {
  // Catching exception by class.
  if (error instanceof EmailTakenError) {
    console.log('E-Mail validation failed!', error);
  } else {
    // If failed to catch, throwing it higher.
    console.log('Unknown error', error);
    throw error;
  }
}


try {
  // Throwing RequestValidationError exception.
  throw new RequestValidationError();
} catch (error) {
  // Catching error by base (parent) class.
  if (error instanceof AppError) {
    console.log('Some application error occurred!', error);
  } else {
    console.log('Unknown error', error);
    throw error;
  }
}

Feedback

It works great for my application, however criticism is welcomed.

Luka Vidaković

Custom error types in node can provide a clearer picture of a failure. Relying on generic errors often leaves us guessing what had happened down the chain. Custom errors can help us identify certain, well known sets of failures and even subclass them for a more generalized handler functions.

In this series of posts we’ll go from constructing a simplest possible custom error(this post) to defining a few, well known HTTP errors and using them inside an Express.js HTTP server framework to craft automatic error responses.

Simplest way to create a custom error type is to just extend an Error’s prototype and initialize the original Error through a constructor:

class MyError extends Error {
  constructor(message) {
    super(message)
  }
}

Enter fullscreen mode

Exit fullscreen mode

That’s it!

The message we pass from the constructor to the «super» call is actually the same parameter you’d pass with the new Error('Something failed!'). Message is just forwarded to the same constructor to set up an error with a message and a stack trace.

There are 2 small things to fix though. If you log out the error created with MyError class:

const error = new MyError('problem')
console.log(error)

Enter fullscreen mode

Exit fullscreen mode

You’ll notice that error type is logged as «Error»:

Error: problem
    at <anonymous>:1:15

Enter fullscreen mode

Exit fullscreen mode

To fix this we just need to augment our error object with a «name» property inside constructor:

  constructor(message) {
    super(message)
    this.name = 'MyError'
  }

Enter fullscreen mode

Exit fullscreen mode

Now if we try previous example we’ll see something like:

MyError: problem
    at <anonymous>:1:15

Enter fullscreen mode

Exit fullscreen mode

1/2 fixed. The only thing remaining is that our stack trace might include the mention of our custom error class constructor. We don’t want to see an error creation in our stack frames, only the real code that caused the issue. Fix is simple, single additional line in the constructor will take care of that:

  Error.captureStackTrace(this, MyError)

Enter fullscreen mode

Exit fullscreen mode

This will omit all of the stack frames invoked by code inside MyError itself.

The final code is:

class MyError extends Error {
  constructor(message) {
    super(message)
    this.name = 'MyError'
    Error.captureStackTrace(this, MyError)
  }
}

Enter fullscreen mode

Exit fullscreen mode

In next post we’ll go from custom error type to a custom error subtype that will enable us to treat all of our custom error types in a generic way.

Update your code to assign your prototype to the Error.prototype and the instanceof and your asserts work.

function NotImplementedError(message = "") {
    this.name = "NotImplementedError";
    this.message = message;
}
NotImplementedError.prototype = Error.prototype;

However, I would just throw your own object and just check the name property.

throw {name : "NotImplementedError", message : "too lazy to implement"}; 

Edit based on comments

After looking at the comments and trying to remember why I would assign prototype to Error.prototype instead of new Error() like Nicholas Zakas did in his article, I created a jsFiddle with the code below:

function NotImplementedError(message = "") {
  this.name = "NotImplementedError";
  this.message = message;
}
NotImplementedError.prototype = Error.prototype;

function NotImplementedError2(message = "") {
  this.message = message;
}
NotImplementedError2.prototype = new Error();

try {
  var e = new NotImplementedError("NotImplementedError message");
  throw e;
} catch (ex1) {
  console.log(ex1.stack);
  console.log("ex1 instanceof NotImplementedError = " + (ex1 instanceof NotImplementedError));
  console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
  console.log("ex1.name = " + ex1.name);
  console.log("ex1.message = " + ex1.message);
}

try {
  var e = new NotImplementedError2("NotImplementedError2 message");
  throw e;
} catch (ex1) {
  console.log(ex1.stack);
  console.log("ex1 instanceof NotImplementedError2 = " + (ex1 instanceof NotImplementedError2));
  console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
  console.log("ex1.name = " + ex1.name);
  console.log("ex1.message = " + ex1.message);
}

The console output was this.

undefined
ex1 instanceof NotImplementedError = true
ex1 instanceof Error = true
ex1.name = NotImplementedError
ex1.message = NotImplementedError message
Error
    at window.onload (http://fiddle.jshell.net/MwMEJ/show/:29:34)
ex1 instanceof NotImplementedError2 = true
ex1 instanceof Error = true
ex1.name = Error
ex1.message = NotImplementedError2 message

This confirmes the «problem» I ran into was the stack property of the error was the line number where new Error() was created, and not where the throw e occurred. However, that may be better that having the side effect of a NotImplementedError.prototype.name = "NotImplementedError" line affecting the Error object.

Also, notice with NotImplementedError2, when I don’t set the .name explicitly, it is equal to «Error». However, as mentioned in the comments, because that version sets prototype to new Error(), I could set NotImplementedError2.prototype.name = "NotImplementedError2" and be OK.

Abhay's user avatar

Abhay

3,0411 gold badge19 silver badges28 bronze badges

answered May 16, 2009 at 3:51

Kevin Hakanson's user avatar

Kevin HakansonKevin Hakanson

40.8k23 gold badges125 silver badges154 bronze badges

22

In ES2015, you can use class to do this cleanly:

class NotImplemented extends Error {
  constructor(message = "", ...args) {
    super(message, ...args);
    this.message = message + " has not yet been implemented.";
  }
}

This does not modify the global Error prototype, allows you to customize message, name, and other attributes, and properly captures the stack. It’s also pretty readable.

Of course, you may need to use a tool like babel if your code will be running on older browsers.

answered Jun 14, 2017 at 16:09

rattray's user avatar

rattrayrattray

4,7961 gold badge33 silver badges25 bronze badges

2

All of the above answers are terrible awful — really. Even the one with 107 ups! The real answer is here guys:

Inheriting from the Error object — where is the message property?

TL;DR:

A. The reason message isn’t being set is that Error is a function that returns a new Error object and does not manipulate this in any way.

B. The way to do this right is to return the result of the apply from the constructor, as well as setting the prototype in the usual complicated javascripty way:

function MyError() {
    var temp = Error.apply(this, arguments);
    temp.name = this.name = 'MyError';
    this.message = temp.message;
    if(Object.defineProperty) {
        // getter for more optimizy goodness
        /*this.stack = */Object.defineProperty(this, 'stack', { 
            get: function() {
                return temp.stack
            },
            configurable: true // so you can change it if you want
        })
    } else {
        this.stack = temp.stack
    }
}
//inherit prototype using ECMAScript 5 (IE 9+)
MyError.prototype = Object.create(Error.prototype, {
    constructor: {
        value: MyError,
        writable: true,
        configurable: true
    }
});

var myError = new MyError("message");
console.log("The message is: '" + myError.message + "'"); // The message is: 'message'
console.log(myError instanceof Error); // true
console.log(myError instanceof MyError); // true
console.log(myError.toString()); // MyError: message
console.log(myError.stack); // MyError: message n 
// <stack trace ...>


 
//for EMCAScript 4 or ealier (IE 8 or ealier), inherit prototype this way instead of above code:
/*
var IntermediateInheritor = function() {};
IntermediateInheritor.prototype = Error.prototype;
MyError.prototype = new IntermediateInheritor();
*/

You could probably do some trickery to enumerate through all the non-enumerable properties of the tmp Error to set them rather than explicitly setting only stack and message, but the trickery isn’t supported in ie<9

Community's user avatar

answered Jul 26, 2013 at 21:12

B T's user avatar

B TB T

55.4k34 gold badges184 silver badges202 bronze badges

11

If anyone is curious on how to create a custom error and get the stack trace:

function CustomError(message) {
  this.name = 'CustomError';
  this.message = message || '';
  var error = new Error(this.message);
  error.name = this.name;
  this.stack = error.stack;
}
CustomError.prototype = Object.create(Error.prototype);

try {
  throw new CustomError('foobar');
}
catch (e) {
  console.log('name:', e.name);
  console.log('message:', e.message);
  console.log('stack:', e.stack);
}

ThomasReggi's user avatar

ThomasReggi

52.7k82 gold badges227 silver badges409 bronze badges

answered Dec 22, 2014 at 2:12

risto's user avatar

ristoristo

1,2649 silver badges11 bronze badges

class NotImplementedError extends Error {
  constructor(message) {
    super(message);
    this.message = message;
  }
}
NotImplementedError.prototype.name = 'NotImplementedError';
module.exports = NotImplementedError;

and

try {
  var e = new NotImplementedError("NotImplementedError message");
  throw e;
} catch (ex1) {
  console.log(ex1.stack);
  console.log("ex1 instanceof NotImplementedError = " + (ex1 instanceof NotImplementedError));
  console.log("ex1 instanceof Error = " + (ex1 instanceof Error));
  console.log("ex1.name = " + ex1.name);
  console.log("ex1.message = " + ex1.message);
}

It is just a class representation of this answer.

output

NotImplementedError: NotImplementedError message
  ...stacktrace
ex1 instanceof NotImplementedError = true
ex1 instanceof Error = true
ex1.name = NotImplementedError
ex1.message = NotImplementedError message

answered Aug 10, 2020 at 8:57

gramcha's user avatar

gramchagramcha

6829 silver badges16 bronze badges

This section of the standard may explain why the Error.apply call doesn’t initialize the object:

15.11.1 The Error Constructor Called as a Function

When Error is called as a function rather than as a constructor, it creates and
initialises a new Error object. Thus the function call Error(…) is
equivalent to the object creation expression new Error(…) with the
same arguments.

In this case the Error function probably determines that it’s not being called as a constructor, so it returns a new Error instance rather than initializing the this object.

Testing with the following code seems to demonstrate that this is in fact what’s happening:

function NotImplementedError() { 
   var returned = Error.apply(this, arguments);
   console.log("returned.message = '" + returned.message + "'");
   console.log("this.message = '" + this.message + "'");
}
NotImplementedError.prototype = new Error();

var nie = new NotImplementedError("some message");

The following output is generated when this is run:

returned.message = 'some message'
this.message = ''

answered Aug 12, 2011 at 6:31

Dave's user avatar

DaveDave

4,3901 gold badge34 silver badges39 bronze badges

9

I like to do it like this:

  • Make use of name so toString() throws "{code}: {message}"
  • Return same thing to super so it appears the same in the stacktrace
  • Attach code to error.code as checking/parsing a code is better in code than checking a message, which you might want to localize for example
  • Attach message to error.message as an alternative to error.toString()
class AppException extends Error {
  constructor(code, message) {
    const fullMsg = message ? `${code}: ${message}` : code;
    super(fullMsg);
    this.name = code;
    this.code = code;
    this.message = fullMsg;
  }
  
  toString() {
    return this.message;
  }
}

// Just a code
try {
  throw new AppException('FORBIDDEN');
} catch(e) {
  console.error(e);
  console.error(e.toString());
  console.log(e.code === 'FORBIDDEN');
}

// A code and a message
try {
  throw new AppException('FORBIDDEN', 'You don't have access to this page');
} catch(e) {
  console.error(e);
  console.error(e.toString());
  console.log(e.code === 'FORBIDDEN');
}

answered Sep 21, 2018 at 23:42

Dominic's user avatar

DominicDominic

60.4k20 gold badges135 silver badges158 bronze badges

function InvalidValueError(value, type) {
    this.message = "Expected `" + type.name + "`: " + value;
    var error = new Error(this.message);
    this.stack = error.stack;
}
InvalidValueError.prototype = new Error();
InvalidValueError.prototype.name = InvalidValueError.name;
InvalidValueError.prototype.constructor = InvalidValueError;

answered Nov 20, 2013 at 5:43

Pierre Voisin's user avatar

1

Accoring to Joyent you shouldn’t mess with the stack property (which I see in lots of answers given here), because it will have a negative impact on performance. Here is what they say:

stack: generally, don’t mess with this. Don’t even augment it. V8 only computes it if someone actually reads the property, which improves performance dramatically for handlable errors. If you read the property just to augment it, you’ll end up paying the cost even if your caller doesn’t need the stack.

I like and would like to mention their idea of wrapping the original error which is a nice replacement for passing on the stack.

So here is how I create a custom error, considering the above mentioned:

es5 version:

function RError(options) {
    options = options || {}; // eslint-disable-line no-param-reassign
    this.name = options.name;
    this.message = options.message;
    this.cause = options.cause;

    // capture stack (this property is supposed to be treated as private)
    this._err = new Error();

    // create an iterable chain
    this.chain = this.cause ? [this].concat(this.cause.chain) : [this];
}
RError.prototype = Object.create(Error.prototype, {
    constructor: {
        value: RError,
        writable: true,
        configurable: true
    }
});

Object.defineProperty(RError.prototype, 'stack', {
    get: function stack() {
        return this.name + ': ' + this.message + 'n' + this._err.stack.split('n').slice(2).join('n');
    }
});

Object.defineProperty(RError.prototype, 'why', {
    get: function why() {
        var _why = this.name + ': ' + this.message;
        for (var i = 1; i < this.chain.length; i++) {
            var e = this.chain[i];
            _why += ' <- ' + e.name + ': ' + e.message;
        }
        return _why;
    }
});

// usage

function fail() {
    throw new RError({
        name: 'BAR',
        message: 'I messed up.'
    });
}

function failFurther() {
    try {
        fail();
    } catch (err) {
        throw new RError({
            name: 'FOO',
            message: 'Something went wrong.',
            cause: err
        });
    }
}

try {
    failFurther();
} catch (err) {
    console.error(err.why);
    console.error(err.stack);
    console.error(err.cause.stack);
}

es6 version:

class RError extends Error {
    constructor({name, message, cause}) {
        super();
        this.name = name;
        this.message = message;
        this.cause = cause;
    }
    [Symbol.iterator]() {
        let current = this;
        let done = false;
        const iterator = {
            next() {
                const val = current;
                if (done) {
                    return { value: val, done: true };
                }
                current = current.cause;
                if (!val.cause) {
                    done = true;
                }
                return { value: val, done: false };
            }
        };
        return iterator;
    }
    get why() {
        let _why = '';
        for (const e of this) {
            _why += `${_why.length ? ' <- ' : ''}${e.name}: ${e.message}`;
        }
        return _why;
    }
}

// usage

function fail() {
    throw new RError({
        name: 'BAR',
        message: 'I messed up.'
    });
}

function failFurther() {
    try {
        fail();
    } catch (err) {
        throw new RError({
            name: 'FOO',
            message: 'Something went wrong.',
            cause: err
        });
    }
}

try {
    failFurther();
} catch (err) {
    console.error(err.why);
    console.error(err.stack);
    console.error(err.cause.stack);
}

I’ve put my solution into a module, here it is: https://www.npmjs.com/package/rerror

answered Oct 19, 2016 at 9:48

borisdiakur's user avatar

borisdiakurborisdiakur

9,5977 gold badges66 silver badges98 bronze badges

I had a similar issue to this. My error needs to be an instanceof both Error and NotImplemented, and it also needs to produce a coherent backtrace in the console.

My solution:

var NotImplemented = (function() {
  var NotImplemented, err;
  NotImplemented = (function() {
    function NotImplemented(message) {
      var err;
      err = new Error(message);
      err.name = "NotImplemented";
      this.message = err.message;
      if (err.stack) this.stack = err.stack;
    }
    return NotImplemented;
  })();
  err = new Error();
  err.name = "NotImplemented";
  NotImplemented.prototype = err;

  return NotImplemented;
}).call(this);

// TEST:
console.log("instanceof Error: " + (new NotImplemented() instanceof Error));
console.log("instanceof NotImplemented: " + (new NotImplemented() instanceofNotImplemented));
console.log("message: "+(new NotImplemented('I was too busy').message));
throw new NotImplemented("just didn't feel like it");

Result of running with node.js:

instanceof Error: true
instanceof NotImplemented: true
message: I was too busy

/private/tmp/t.js:24
throw new NotImplemented("just didn't feel like it");
      ^
NotImplemented: just didn't feel like it
    at Error.NotImplemented (/Users/colin/projects/gems/jax/t.js:6:13)
    at Object.<anonymous> (/Users/colin/projects/gems/jax/t.js:24:7)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:487:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

The error passes all 3 of my criteria, and although the stack property is nonstandard, it is supported in most newer browsers which is acceptable in my case.

answered May 16, 2012 at 11:56

sinisterchipmunk's user avatar

0

I used the Constructor Pattern to create the new error object. I defined the prototype chain such as an Error instance. See the MDN Error constructor reference.

You can check this snippet on this gist.

IMPLEMENTATION

// Creates user-defined exceptions
var CustomError = (function() {
  'use strict';

  //constructor
  function CustomError() {
    //enforces 'new' instance
    if (!(this instanceof CustomError)) {
      return new CustomError(arguments);
    }
    var error,
      //handles the arguments object when is passed by enforcing a 'new' instance
      args = Array.apply(null, typeof arguments[0] === 'object' ? arguments[0] : arguments),
      message = args.shift() || 'An exception has occurred';

    //builds the message with multiple arguments
    if (~message.indexOf('}')) {
      args.forEach(function(arg, i) {
        message = message.replace(RegExp('\{' + i + '}', 'g'), arg);
      });
    }

    //gets the exception stack
    error = new Error(message);
    //access to CustomError.prototype.name
    error.name = this.name;

    //set the properties of the instance
    //in order to resemble an Error instance
    Object.defineProperties(this, {
      stack: {
        enumerable: false,
        get: function() { return error.stack; }
      },
      message: {
        enumerable: false,
        value: message
      }
    });
  }

  // Creates the prototype and prevents the direct reference to Error.prototype;
  // Not used new Error() here because an exception would be raised here,
  // but we need to raise the exception when CustomError instance is created.
  CustomError.prototype = Object.create(Error.prototype, {
    //fixes the link to the constructor (ES5)
    constructor: setDescriptor(CustomError),
    name: setDescriptor('JSU Error')
  });

  function setDescriptor(value) {
    return {
      configurable: false,
      enumerable: false,
      writable: false,
      value: value
    };
  }

  //returns the constructor
  return CustomError;
}());

USAGE

The CustomError constructor can receive many arguments to build the message, e.g.

var err1 = new CustomError("The url of file is required"),
    err2 = new CustomError("Invalid Date: {0}", +"date"),
    err3 = new CustomError("The length must be greater than {0}", 4),
    err4 = new CustomError("Properties .{0} and .{1} don't exist", "p1", "p2");

throw err4;

And this is how the custom error looks:

Custom error prototype chain

answered Feb 16, 2015 at 17:33

jherax's user avatar

jheraxjherax

5,2185 gold badges36 silver badges49 bronze badges

2

This is my implementation:

class HttpError extends Error {
  constructor(message, code = null, status = null, stack = null, name = null) {
    super();
    this.message = message;
    this.status = 500;

    this.name = name || this.constructor.name;
    this.code = code || `E_${this.name.toUpperCase()}`;
    this.stack = stack || null;
  }

  static fromObject(error) {
    if (error instanceof HttpError) {
      return error;
    }
    else {
      const { message, code, status, stack } = error;
      return new ServerError(message, code, status, stack, error.constructor.name);
    }
  }

  expose() {
    if (this instanceof ClientError) {
      return { ...this };
    }
    else {
      return {
        name: this.name,
        code: this.code,
        status: this.status,
      }
    }
  }
}

class ServerError extends HttpError {}

class ClientError extends HttpError { }

class IncorrectCredentials extends ClientError {
  constructor(...args) {
    super(...args);
    this.status = 400;
  }
}

class ResourceNotFound extends ClientError {
  constructor(...args) {
    super(...args);
    this.status = 404;
  }
}

Example usage #1:

app.use((req, res, next) => {
  try {
    invalidFunction();
  }
  catch (err) {
    const error = HttpError.fromObject(err);
    return res.status(error.status).send(error.expose());
  }
});

Example usage #2:

router.post('/api/auth', async (req, res) => {
  try {
    const isLogged = await User.logIn(req.body.username, req.body.password);

    if (!isLogged) {
      throw new IncorrectCredentials('Incorrect username or password');
    }
    else {
      return res.status(200).send({
        token,
      });
    }
  }
  catch (err) {
    const error = HttpError.fromObject(err);
    return res.status(error.status).send(error.expose());
  }
});

answered Sep 12, 2018 at 14:56

Rafal Enden's user avatar

Rafal EndenRafal Enden

2,9381 gold badge21 silver badges16 bronze badges

1

I just had to implement something like this and found that the stack was lost in my own error implementation. What I had to do was create a dummy error and retrieve the stack from that:

My.Error = function (message, innerException) {
    var err = new Error();
    this.stack = err.stack; // IMPORTANT!
    this.name = "Error";
    this.message = message;
    this.innerException = innerException;
}
My.Error.prototype = new Error();
My.Error.prototype.constructor = My.Error;
My.Error.prototype.toString = function (includeStackTrace) {
    var msg = this.message;
    var e = this.innerException;
    while (e) {
        msg += " The details are:n" + e.message;
        e = e.innerException;
    }
    if (includeStackTrace) {
        msg += "nnStack Trace:nn" + this.stack;
    }
    return msg;
}

answered May 31, 2012 at 11:14

Jules's user avatar

JulesJules

4,3193 gold badges41 silver badges72 bronze badges

1

The constructor needs to be like a factory method and return what you want. If you need additional methods/properties, you can add them to the object before returning it.

function NotImplementedError(message) { return new Error("Not implemented", message); }

x = new NotImplementedError();

Though I’m not sure why you’d need to do this. Why not just use new Error... ? Custom exceptions don’t really add much in JavaScript (or probably any untyped language).

answered Apr 23, 2009 at 22:42

pluckyglen's user avatar

pluckyglenpluckyglen

8197 silver badges9 bronze badges

1

This is implemented nicely in the Cesium DeveloperError:

  • Docs
  • Source

In it’s simplified form:

var NotImplementedError = function(message) {
    this.name = 'NotImplementedError';
    this.message = message;
    this.stack = (new Error()).stack;
}

// Later on...

throw new NotImplementedError();

answered Jan 27, 2014 at 1:34

Aram Kocharyan's user avatar

Aram KocharyanAram Kocharyan

20k11 gold badges80 silver badges96 bronze badges

2

At the expense of not being able to use instanceof, the following preserves the original stack trace and doesn’t use any non-standard tricks.

// the function itself
var fixError = function(err, name) {
    err.name = name;
    return err;
}

// using the function
try {
    throw fixError(new Error('custom error message'), 'CustomError');
} catch (e) {
    if (e.name == 'CustomError')
        console.log('Wee! Custom Error! Msg:', e.message);
    else
        throw e; // unhandled. let it propagate upwards the call stack
}

answered Apr 28, 2013 at 14:58

Gima's user avatar

GimaGima

1,87219 silver badges23 bronze badges

3

Another alternative , might not work in all enviroments.Atleast assured it works in nodejs 0.8
This approach uses a non standard way of modifying the internal proto prop

function myError(msg){ 
      var e = new Error(msg); 
      _this = this; 
      _this.__proto__.__proto__ = e;
}

kleopatra's user avatar

kleopatra

50.8k28 gold badges99 silver badges207 bronze badges

answered Jul 30, 2013 at 9:00

Chandu's user avatar

ChanduChandu

4,5512 gold badges16 silver badges13 bronze badges

If you are using Node/Chrome. The following snippet will get you extension which meets the following requirements.

  • err instanceof Error
  • err instanceof CustomErrorType
  • console.log() returns [CustomErrorType] when created with a message
  • console.log() returns [CustomErrorType: message] when created without a message
  • throw/stack provides the information at the point the error was created.
  • Works optimally in Node.JS, and Chrome.
  • Will pass instanceof checks in Chrome, Safari, Firefox and IE 8+, but will not have a valid stack outside of Chrome/Safari. I’m OK with that because I can debug in chrome, but code which requires specific error types will still function cross browser. If you need Node only you can easily remove the if statements and you’re good to go.

Snippet

var CustomErrorType = function(message) {
    if (Object.defineProperty) {
        Object.defineProperty(this, "message", {
            value : message || "",
            enumerable : false
        });
    } else {
        this.message = message;
    }

    if (Error.captureStackTrace) {
        Error.captureStackTrace(this, CustomErrorType);
    }
}

CustomErrorType.prototype = new Error();
CustomErrorType.prototype.name = "CustomErrorType";

Usage

var err = new CustomErrorType("foo");

Output

var err = new CustomErrorType("foo");
console.log(err);
console.log(err.stack);

[CustomErrorType: foo]
CustomErrorType: foo
    at Object.<anonymous> (/errorTest.js:27:12)
    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

/errorTest.js:30
        throw err;
              ^
CustomErrorType: foo
    at Object.<anonymous> (/errorTest.js:27:12)
    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

answered Oct 24, 2014 at 20:31

Owen Allen's user avatar

Owen AllenOwen Allen

11k8 gold badges50 silver badges61 bronze badges

The following worked for me taken from the official Mozilla documentation Error.

function NotImplementedError(message) {
    var instance = new Error(message);
    instance.name = 'NotImplementedError';

    Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
    if (Error.captureStackTrace) {
        Error.captureStackTrace(instance, NotImplementedError);
    }
    return instance;
}

NotImplementedError.prototype = Object.create(Error.prototype, {
    constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
    }
});

answered Jan 6, 2020 at 15:21

Zhunio's user avatar

0

Here is my solution for supporting pre-es2015 browsers. It does not do any fancy prototype tweaking and will not break debuggers.

/**  Custom Errors
    // Depends on underscore js
    // This will declare an CustError() class in both 'this' and '_exports' namespaces
    // ctor is optional
    declare_cust_error(function CustError(){}, {ns: [this, _exports], ctor: 
        function cust_err_ctor(instance, clazz, name, msg, info){
            q$.called(arguments)
        }
    })

    // Usage:
    // Second param (pojso) is optional
    try {
        throw CustError.create("foo", {k1: 'v1', k2: 'v2'})
    }catch(ex){
        if(CustError.is_inst(ex)){
            console.error("its a CustError", ex)
        } else {
            throw ex
        }
    }

**/
function declare_cust_error(error_class, opts){
    var p, c, cp
    if(!error_class||!(p=error_class.prototype))throw new Error("error_class must be a Class")
    try{
        c = p.constructor; cp = c.toString()
    }catch(ex){}
    if(!cp || cp.indexOf('function ') != 0 || cp.indexOf('[native code]') > 0)
        throw new Error("error_class must be a classic proto class (pre-es6) but got: " + error_class.toString())

    opts=opts||{}
    
    error_class.__is_cust_error__ = true
    error_class.__cust_error_name__ = c.name

    error_class.create = function cust_error_create(msg, info){
        var instance = new Error(msg)
        instance.info = info
        instance.__is_cust_error__ = true
        instance.__cust_error_name__ = c.name
        if(_.isFunction(opts.ctor)){
            opts.ctor(instance, error_class, c.name, msg, info)
        }
        return instance
    }

    error_class.is_inst = function cust_error_is_inst(instanace){
        return ( (instanace instanceof Error) && instanace.__cust_error_name__ === error_class.__cust_error_name__ )
    }
    
    // Declare error in namespace(s)
    _.each(_.isArray(opts.ns)?opts.ns:[opts.ns], function(ns){ ns[c.name] = error_class })

    return error_class

}

answered Oct 24, 2022 at 16:55

Timothy C. Quinn's user avatar

Timothy C. QuinnTimothy C. Quinn

3,4211 gold badge32 silver badges42 bronze badges

A lot of the methods above won’t work.

Errors

The last one is an actual error. If you use a string, it looks good, but it doesn’t give a stack trace. If you throw with Error, you can’t have "Uncaught BadError: bad", so you’ll have to remove the custom error (sadly). If you throw an object, it looks kind of off, and the final one is just an average error.

This method creates an error with a custom name while preserving stack tracing:

var errProto = Object.create(Error.prototype, {
  constructor: {
    value: Error,
    enumerable: false,
    writable: true,
    configurable: true
  }
})
var isFirefox = !!window.InstallTrigger
// Hide stack for Firefox only, as stacks can cause problems with high "frame" counts.
function createError(name, message, hideStack) {
  if (message == null) {
    message = ""
  }
  var customError = Error(message)
  customError.name = name
  Object.setPrototypeOf(customError, errProto)
  if (isFirefox && hideStack) {
    customError.stack = ""
  } else if (isFirefox) {
    var stack = customError.stack
    var newline = stack.indexOf("n") + 1
    stack = stack.slice(newline)
    customError.stack = stack
    var split = stack.split(":")
    if (split.length > 4) {
      var a = split[3]
      var b = split[4]
      var t = b.slice(0, b.indexOf("n"))
      customError.lineNumber = Number(a)
      customError.columnNumber = Number(t)
    }
  } else {
    var stack = customError.stack
    var split = stack.split("n")
    var secondPart = split.slice(2).join("n")
    stack = split[0] + "n" + secondPart
    customError.stack = stack
    var split = secondPart.split(":")
    var a = split[2]
    var b = split[3]
  }
  throw customError
}

var frame = 0

function aFunction() {
  if (++frame === 100) {
    createError("LazyError", "function getting lazy", false, true)
  } else {
    requestAnimationFrame(aFunction)
  }
}

setTimeout(aFunction, Math.random() * 500)
* {
  font-family: Verdana;
}
Check your inspector!

answered Dec 17, 2022 at 17:15

Infigon's user avatar

InfigonInfigon

4004 silver badges12 bronze badges

Try a new prototype object for each instance of the user defined error type. It allows instanceof checks to behave as usual plus type and message are correctly reported in Firefox and V8 (Chome, nodejs).

function NotImplementedError(message){
    if(NotImplementedError.innercall===undefined){
        NotImplementedError.innercall = true;
        NotImplementedError.prototype = new Error(message);
        NotImplementedError.prototype.name = "NotImplementedError";
        NotImplementedError.prototype.constructor = NotImplementedError;

        return new NotImplementedError(message);
    }
    delete NotImplementedError.innercall;
}

Note that an additional entry will preceed the otherwise correct stack.

answered Aug 19, 2012 at 21:09

Augustus Kling's user avatar

Augustus KlingAugustus Kling

3,2931 gold badge21 silver badges25 bronze badges

1

This is fastest way to do it:

    let thisVar = false

    if (thisVar === false) {
            throw new Error("thisVar is false. It should be true.")
    }

answered Feb 5, 2020 at 17:19

jlhs's user avatar

jlhsjlhs

1037 bronze badges

easier way. You could make your object inherit from the Error object.
Example:

function NotImplementError(message)
{
    this.message = message;
    Error.call();
    Error.call(message);
} 

what we are doing is using the function call() which call the constructor of the Error class so is basicly the same thing as implementing a class inheritance in other object oriented languages.

answered Mar 6, 2013 at 19:27

Paulo Enmanuel's user avatar

0

MDN has an excellent example:

try {
  throw new Error('Whoops!');
} catch (e) {
  console.log(e.name + ': ' + e.message);
}

answered Sep 4, 2017 at 21:59

Ronnie Royston's user avatar

Ronnie RoystonRonnie Royston

15.7k6 gold badges73 silver badges87 bronze badges

I’m surprised how little custom errors are used in Node.js and I don’t understand why.

I was integrating an open source library last week into a project and I was trying to write unit tests covering all failure cases one could expect with the library. The library, however, didn’t make use of explicit error cases. This left me having to parse the error message to determine what type of error I was experiencing:

expect(() => {
   executeWithInvalidInput(['foo', 'bar', 'hello', 'world']);
}).to.throw(/Invalid input: "foo" should have come after "bar"/);

I see two distinct issues with throwing a generic Error:

  1. Cannot differentiate errors by object type (prototype hierarchy).
  2. Feedback returned by error is limited to the Error.message.

Using the previous example, what if we could instead?:

try {
   executeWithInvalidInput(['foo', 'bar', 'hello', 'world']);
   expect.fail();
} catch (error) {
   expect(error).to.be.an.instanceOf(InvalidInputOrderError);
   expect(error.data.violator).to.eq('foo');
}

This version of the test case is much more specific and has the added benefit of verifying the exact input that caused the problem. It also prevents the exact nature of the error from being hidden. In the case of that third party library, their test cases were not actually catching the right error: https://github.com/marcelklehr/toposort/issues/24.

So how do we create a custom error in JavaScript?

Later versions of Node.js make the process simple by allowing you to extend the Error class:

class DomainError extends Error {
  constructor(message) {
    super(message);
   // Ensure the name of this error is the same as the class name
    this.name = this.constructor.name;
   // This clips the constructor invocation from the stack trace.
   // It's not absolutely essential, but it does make the stack trace a little nicer.
   //  @see Node.js reference (bottom)
    Error.captureStackTrace(this, this.constructor);
  }
}

class ResourceNotFoundError extends DomainError {
  constructor(resource, query) {
    super(`Resource ${resource} was not found.`);
    this.data = { resource, query };
  }
}

// I do something like this to wrap errors from other frameworks.
// Correction thanks to @vamsee on Twitter:
// https://twitter.com/lakamsani/status/1035042907890376707
class InternalError extends DomainError {
  constructor(error) {
    super(error.message);
    this.data = { error };
  }
}

module.exports = {
  ResourceNotFoundError,
  InternalError,  
};

Using custom errors are as natural as generic ones and stylistically look much better:

const Person = require('../models/person');
const { ResourceNotFoundError, InternalError } = require('../errors');

async function findPerson(name) {
  const query = { name };
  let person;
  try {
    person = await Person.find(query);
  } catch (error) {
    throw new InternalError(error);
  }
  if (!person) {
    throw new ResourceNotFoundError('person', query);
  }
  return person;
}

module.exports = findPerson;

Now when I test the function, I can ensure that unexpected error cases aren’t hidden by the test validation. For instance, if an Internal Error occurs, it will not be hidden by the generic test case:

const { describe, it } = require('mocha');
const { expect } = require('chai');
const { ResourceNotFoundError, InternalError } = require('../lib/errors');

describe('when looking up People', () => {
  it('should throw an error if the person cannot be found', async () => {
    expect(() => await findPerson('John Doe'))
      .to.throw(ResourceNotFoundError);
  });
});

I also find this to be an excellent strategy for mapping domain errors to protocol ones (keeping your business layer clean). Here is an example using the strategy with Hapi.js:

// Boom is a Hapi framework for creating HTTP error responses.
const Boom = require('boom');
const { ResourceNotFoundError, InternalError } = require('../lib/errors');
const findPerson = require('../lib/people/find');

// This would be a common utility function used across handlers
function mapDomainErrorToHttpResponse(error) {
  if (error instanceof ResourceNotFoundError) {
    return Boom.notFound(error.message, error.data.query);
  }
  return Boom.badImplementation('Internal Error');
}

server.route({
  method: 'GET',
  path: '/people/{name}',
  async handler(request, reply) {
    try {
      reply(await findPerson(request.params.name));
    } catch (error) {
      reply(mapDomainErrorToHttpResponse(error));
    }
  },
});

Hopefully, you will agree that custom errors are worth the effort. They don’t require a lot of extra code and make the intent of your error extremely clear. If you are developing a public facing API, don’t be afraid of exporting those error types so consumers can catch them. I promise you the explicit structure of the error will be appreciated by your users.

Note: I mention the marcelklehr/toposort library as an example that inspired this post, but I hope you don’t consider this a criticism of the library or author. I’m extremely grateful for his (and fellow contributors) work — toposort provides essential functionality for an upcoming DI framework project I’m working on.

Resources

Node.js Error reference: https://nodejs.org/api/errors.html

Node.js Error.capatureStackTrace: https://nodejs.org/api/errors.html#errors_error_capturestacktrace_targetobject_constructoropt

This Gist inspired my original Error implementation: https://gist.github.com/slavafomin/b164e3e710a6fc9352c934b9073e7216

Stumbling my way through the great wastelands of enterprise software development.

If you’ve been writing anything more than «Hello world» programs, you are probably familiar with the concept of errors in programming. They are mistakes in your code, often referred to as «bugs», that cause a program to fail or behave unexpectedly. Unlike some languages, such as Go and Rust, where you are forced to interact with potential errors every step of the way, it’s possible to get by without a coherent error handling strategy in JavaScript and Node.js.

It doesn’t have to be this way, though, because Node.js error handling can be quite straightforward once you are familiar with the patterns used to create, deliver, and handle potential errors. This article aims to introduce you to these patterns so that you can make your programs more robust by ensuring that you’ll discover potential errors and handle them appropriately before deploying your application to production!

What are errors in Node.js

An error in Node.js is any instance of the Error object. Common examples include built-in error classes, such as ReferenceError, RangeError, TypeError, URIError, EvalError, and SyntaxError. User-defined errors can also be created by extending the base Error object, a built-in error class, or another custom error. When creating errors in this manner, you should pass a message string that describes the error. This message can be accessed through the message property on the object. The Error object also contains a name and a stack property that indicate the name of the error and the point in the code at which it is created, respectively.

const userError = new TypeError("Something happened!");
console.log(userError.name); // TypeError
console.log(userError.message); // Something happened!
console.log(userError.stack);
/*TypeError: Something happened!
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:2:19)
    <truncated for brevity>
    at node:internal/main/run_main_module:17:47 */

Once you have an Error object, you can pass it to a function or return it from a function. You can also throw it, which causes the Error object to become an exception. Once you throw an error, it bubbles up the stack until it is caught somewhere. If you fail to catch it, it becomes an uncaught exception, which may cause your application to crash!

How to deliver errors

The appropriate way to deliver errors from a JavaScript function varies depending on whether the function performs a synchronous or asynchronous operation. In this section, I’ll detail four common patterns for delivering errors from a function in a Node.js application.

1. Exceptions

The most common way for functions to deliver errors is by throwing them. When you throw an error, it becomes an exception and needs to be caught somewhere up the stack using a try/catch block. If the error is allowed to bubble up the stack without being caught, it becomes an uncaughtException, which causes the application to exit prematurely. For example, the built-in JSON.parse() method throws an error if its string argument is not a valid JSON object.

function parseJSON(data) {
  return JSON.parse(data);
}

try {
  const result = parseJSON('A string');
} catch (err) {
  console.log(err.message); // Unexpected token A in JSON at position 0
}

To utilize this pattern in your functions, all you need to do is add the throw keyword before an instance of an error. This pattern of error reporting and handling is idiomatic for functions that perform synchronous operations.

function square(num) {
  if (typeof num !== 'number') {
    throw new TypeError(`Expected number but got: ${typeof num}`);
  }

  return num * num;
}

try {
  square('8');
} catch (err) {
  console.log(err.message); // Expected number but got: string
}

2. Error-first callbacks

Due to its asynchronous nature, Node.js makes heavy use of callback functions for much of its error handling. A callback function is passed as an argument to another function and executed when the function has finished its work. If you’ve written JavaScript code for any length of time, you probably know that the callback pattern is heavily used throughout JavaScript code.

Node.js uses an error-first callback convention in most of its asynchronous methods to ensure that errors are checked properly before the results of an operation are used. This callback function is usually the last argument to the function that initiates an asynchronous operation, and it is called once when an error occurs or a result is available from the operation. Its signature is shown below:

function (err, result) {}

The first argument is reserved for the error object. If an error occurs in the course of the asynchronous operation, it will be available via the err argument and result will be undefined. However, if no error occurs, err will be null or undefined, and result will contain the expected result of the operation. This pattern can be demonstrated by reading the contents of a file using the built-in fs.readFile() method:

const fs = require('fs');

fs.readFile('/path/to/file.txt', (err, result) => {
  if (err) {
    console.error(err);
    return;
  }

  // Log the file contents if no error
  console.log(result);
});

As you can see, the readFile() method expects a callback function as its last argument, which adheres to the error-first function signature discussed earlier. In this scenario, the result argument contains the contents of the file read if no error occurs. Otherwise, it is undefined, and the err argument is populated with an error object containing information about the problem (e.g., file not found or insufficient permissions).

Generally, methods that utilize this callback pattern for error delivery cannot know how important the error they produce is to your application. It could be severe or trivial. Instead of deciding for itself, the error is sent up for you to handle. It is important to control the flow of the contents of the callback function by always checking for an error before attempting to access the result of the operation. Ignoring errors is unsafe, and you should not trust the contents of result before checking for errors.

If you want to use this error-first callback pattern in your own async functions, all you need to do is accept a function as the last argument and call it in the manner shown below:

function square(num, callback) {
  if (typeof callback !== 'function') {
    throw new TypeError(`Callback must be a function. Got: ${typeof callback}`);
  }

  // simulate async operation
  setTimeout(() => {
    if (typeof num !== 'number') {
      // if an error occurs, it is passed as the first argument to the callback
      callback(new TypeError(`Expected number but got: ${typeof num}`));
      return;
    }

    const result = num * num;
    // callback is invoked after the operation completes with the result
    callback(null, result);
  }, 100);
}

Any caller of this square function would need to pass a callback function to access its result or error. Note that a runtime exception will occur if the callback argument is not a function.

square('8', (err, result) => {
  if (err) {
    console.error(err)
    return
  }

  console.log(result);
});

You don’t have to handle the error in the callback function directly. You can propagate it up the stack by passing it to a different callback, but make sure not to throw an exception from within the function because it won’t be caught, even if you surround the code in a try/catch block. An asynchronous exception is not catchable because the surrounding try/catch block exits before the callback is executed. Therefore, the exception will propagate to the top of the stack, causing your application to crash unless a handler has been registered for process.on('uncaughtException'), which will be discussed later.

try {
  square('8', (err, result) => {
    if (err) {
      throw err; // not recommended
    }

    console.log(result);
  });
} catch (err) {
  // This won't work
  console.error("Caught error: ", err);
}

Throwing an error inside the callback can crash the Node.js process

3. Promise rejections

Promises are the modern way to perform asynchronous operations in Node.js and are now generally preferred to callbacks because this approach has a better flow that matches the way we analyze programs, especially with the async/await pattern. Any Node.js API that utilizes error-first callbacks for asynchronous error handling can be converted to promises using the built-in util.promisify() method. For example, here’s how the fs.readFile() method can be made to utilize promises:

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

The readFile variable is a promisified version of fs.readFile() in which promise rejections are used to report errors. These errors can be caught by chaining a catch method, as shown below:

readFile('/path/to/file.txt')
  .then((result) => console.log(result))
  .catch((err) => console.error(err));

You can also use promisified APIs in an async function, such as the one shown below. This is the predominant way to use promises in modern JavaScript because the code reads like synchronous code, and the familiar try/catch mechanism can be used to handle errors. It is important to use await before the asynchronous method so that the promise is settled (fulfilled or rejected) before the function resumes its execution. If the promise rejects, the await expression throws the rejected value, which is subsequently caught in a surrounding catch block.

(async function callReadFile() {
  try {
    const result = await readFile('/path/to/file.txt');
    console.log(result);
  } catch (err) {
    console.error(err);
  }
})();

You can utilize promises in your asynchronous functions by returning a promise from the function and placing the function code in the promise callback. If there’s an error, reject with an Error object. Otherwise, resolve the promise with the result so that it’s accessible in the chained .then method or directly as the value of the async function when using async/await.

function square(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof num !== 'number') {
        reject(new TypeError(`Expected number but got: ${typeof num}`));
      }

      const result = num * num;
      resolve(result);
    }, 100);
  });
}

square('8')
  .then((result) => console.log(result))
  .catch((err) => console.error(err));

4. Event emitters

Another pattern that can be used when dealing with long-running asynchronous operations that may produce multiple errors or results is to return an EventEmitter from the function and emit an event for both the success and failure cases. An example of this code is shown below:

const { EventEmitter } = require('events');

function emitCount() {
  const emitter = new EventEmitter();

  let count = 0;
  // Async operation
  const interval = setInterval(() => {
    count++;
    if (count % 4 == 0) {
      emitter.emit(
        'error',
        new Error(`Something went wrong on count: ${count}`)
      );
      return;
    }
    emitter.emit('success', count);

    if (count === 10) {
      clearInterval(interval);
      emitter.emit('end');
    }
  }, 1000);

  return emitter;
}

The emitCount() function returns a new event emitter that reports both success and failure events in the asynchronous operation. The function increments the count variable and emits a success event every second and an error event if count is divisible by 4. When count reaches 10, an end event is emitted. This pattern allows the streaming of results as they arrive instead of waiting until the entire operation is completed.

Here’s how you can listen and react to each of the events emitted from the emitCount() function:

const counter = emitCount();

counter.on('success', (count) => {
  console.log(`Count is: ${count}`);
});

counter.on('error', (err) => {
  console.error(err.message);
});

counter.on('end', () => {
  console.info('Counter has ended');
});

EventEmitter demonstration

As you can see from the image above, the callback function for each event listener is executed independently as soon as the event is emitted. The error event is a special case in Node.js because, if there is no listener for it, the Node.js process will crash. You can comment out the error event listener above and run the program to see what happens.

The error event will cause the application to crash if there is no listener for it

Extending the error object

Using the built-in error classes or a generic instance of the Error object is usually not precise enough to communicate all the different error types. Therefore, it is necessary to create custom error classes to better reflect the types of errors that could occur in your application. For example, you could have a ValidationError class for errors that occur while validating user input, DatabaseError class for database operations, TimeoutError for operations that elapse their assigned timeouts, and so on.

Custom error classes that extend the Error object will retain the basic error properties, such as message, name, and stack, but they can also have properties of their own. For example, a ValidationError can be enhanced by adding meaningful properties, such as the portion of the input that caused the error. Essentially, you should include enough information for the error handler to properly handle the error or construct its own error messages.

Here’s how to extend the built-in Error object in Node.js:

class ApplicationError extends Error {
  constructor(message) {
    super(message);
    // name is set to the name of the class
    this.name = this.constructor.name;
  }
}

class ValidationError extends ApplicationError {
  constructor(message, cause) {
    super(message);
    this.cause = cause
  }
}

The ApplicationError class above is a generic error for the application, while the ValidationError class represents any error that occurs when validating user input. It inherits from the ApplicationError class and augments it with a cause property to specify the input that triggered the error. You can use custom errors in your code just like you would with a normal error. For example, you can throw it:

function validateInput(input) {
  if (!input) {
    throw new ValidationError('Only truthy inputs allowed', input);
  }

  return input;
}

try {
  validateInput(userJson);
} catch (err) {
  if (err instanceof ValidationError) {
    console.error(`Validation error: ${err.message}, caused by: ${err.cause}`);
    return;
  }

  console.error(`Other error: ${err.message}`);
}

Using custom errors

The instanceof keyword should be used to check for the specific error type, as shown above. Don’t use the name of the error to check for the type, as in err.name === 'ValidationError', because it won’t work if the error is derived from a subclass of ValidationError.

Types of errors

It is beneficial to distinguish between the different types of errors that can occur in a Node.js application. Generally, errors can be siloed into two main categories: programmer mistakes and operational problems. Bad or incorrect arguments to a function is an example of the first kind of problem, while transient failures when dealing with external APIs are firmly in the second category.

1. Operational errors

Operational errors are mostly expected errors that can occur in the course of application execution. They are not necessarily bugs but are external circumstances that can disrupt the flow of program execution. In such cases, the full impact of the error can be understood and handled appropriately. Some examples of operational errors in Node.js include the following:

  • An API request fails for some reason (e.g., the server is down or the rate limit exceeded).
  • A database connection is lost, perhaps due to a faulty network connection.
  • The OS cannot fulfill your request to open a file or write to it.
  • The user sends invalid input to the server, such as an invalid phone number or email address.

These situations do not arise due to mistakes in the application code, but they must be handled correctly. Otherwise, they could cause more serious problems.

2. Programmer errors

Programmer errors are mistakes in the logic or syntax of the program that can only be corrected by changing the source code. These types of errors cannot be handled because, by definition, they are bugs in the program. Some examples of programmer errors include:

  • Syntax errors, such as failing to close a curly brace.
  • Type errors when you try to do something illegal, such as performing operations on operands of mismatched types.
  • Bad parameters when calling a function.
  • Reference errors when you misspell a variable, function, or property name.
  • Trying to access a location beyond the end of an array.
  • Failing to handle an operational error.

Operational error handling

Operational errors are mostly predictable, so they must be anticipated and accounted for during the development process. Essentially, handling these types of errors involves considering whether an operation could fail, why it might fail, and what should happen if it does. Let’s consider a few strategies for handling operational errors in Node.js.

1. Report the error up the stack

In many cases, the appropriate action is to stop the flow of the program’s execution, clean up any unfinished processes, and report the error up the stack so that it can be handled appropriately. This is often the correct way to address the error when the function where it occurred is further down the stack such that it does not have enough information to handle the error directly. Reporting the error can be done through any of the error delivery methods discussed earlier in this article.

2. Retry the operation

Reddit 503 error

Network requests to external services may sometimes fail, even if the request is completely valid. This may be due to a transient failure, which can occur if there is a network failure or server overload. Such issues are usually ephemeral, so instead of reporting the error immediately, you can retry the request a few times until it succeeds or until the maximum amount of retries is reached. The first consideration is determining whether it’s appropriate to retry the request. For example, if the initial response HTTP status code is 500, 503, or 429, it might be advantageous to retry the request after a short delay.

You can check whether the Retry-After HTTP header is present in the response. This header indicates the exact amount of time to wait before making a follow-up request. If the Retry-After header does not exist, you need to delay the follow-up request and progressively increase the delay for each consecutive retry. This is known as the exponential back-off strategy. You also need to decide the maximum delay interval and how many times to retry the request before giving up. At that point, you should inform the caller that the target service is unavailable.

3. Send the error to the client

When dealing with external input from users, it should be assumed that the input is bad by default. Therefore, the first thing to do before starting any processes is to validate the input and report any mistakes to the user promptly so that it can be corrected and resent. When delivering client errors, make sure to include all the information that the client needs to construct an error message that makes sense to the user.

4. Abort the program

In the case of unrecoverable system errors, the only reasonable course of action is to log the error and terminate the program immediately. You might not even be able to shut down the server gracefully if the exception is unrecoverable at the JavaScript layer. At that point, a sysadmin may be required to look into the issue and fix it before the program can start again.

Preventing programmer errors

Due to their nature, programmer errors cannot be handled; they are bugs in the program that arise due to broken code or logic, which must subsequently be corrected. However, there are a few things you can do to greatly reduce the frequency at which they occur in your application.

1. Adopt TypeScript

TypeScript is a strongly typed superset of JavaScript. Its primary design goal is to statically identify constructs likely to be errors without any runtime penalties. By adopting TypeScript in your project (with the strictest possible compiler options), you can eliminate a whole class of programmer errors at compile time. For example, after conducting a postmortem analysis of bugs, it was estimated that 38% of bugs in the Airbnb codebase were preventable with TypeScript.

When you migrate your entire project over to TypeScript, errors like «undefined is not a function», syntax errors, or reference errors should no longer exist in your codebase. Thankfully, this is not as daunting as it sounds. Migrating your entire Node.js application to TypeScript can be done incrementally so that you can start reaping the rewards immediately in crucial parts of the codebase. You can also adopt a tool like ts-migrate if you intend to perform the migration in one go.

2. Define the behavior for bad parameters

Many programmer errors result from passing bad parameters. These might be due not only to obvious mistakes, such as passing a string instead of a number, but also to subtle mistakes, such as when a function argument is of the correct type but outside the range of what the function can handle. When the program is running and the function is called that way, it might fail silently and produce a wrong value, such as NaN. When the failure is eventually noticed (usually after traveling through several other functions), it might be difficult to locate its origins.

You can deal with bad parameters by defining their behavior either by throwing an error or returning a special value, such as null, undefined, or -1, when the problem can be handled locally. The former is the approach used by JSON.parse(), which throws a SyntaxError exception if the string to parse is not valid JSON, while the string.indexOf() method is an example of the latter. Whichever you choose, make sure to document how the function deals with errors so that the caller knows what to expect.

3. Automated testing

On its own, the JavaScript language doesn’t do much to help you find mistakes in the logic of your program, so you have to run the program to determine whether it works as expected. The presence of an automated test suite makes it far more likely that you will spot and fix various programmer errors, especially logic errors. They are also helpful in ascertaining how a function deals with atypical values. Using a testing framework, such as Jest or Mocha, is a good way to get started with unit testing your Node.js applications.

Uncaught exceptions and unhandled promise rejections

Uncaught exceptions and unhandled promise rejections are caused by programmer errors resulting from the failure to catch a thrown exception and a promise rejection, respectively. The uncaughtException event is emitted when an exception thrown somewhere in the application is not caught before it reaches the event loop. If an uncaught exception is detected, the application will crash immediately, but you can add a handler for this event to override this behavior. Indeed, many people use this as a last resort way to swallow the error so that the application can continue running as if nothing happened:

// unsafe
process.on('uncaughtException', (err) => {
  console.error(err);
});

However, this is an incorrect use of this event because the presence of an uncaught exception indicates that the application is in an undefined state. Therefore, attempting to resume normally without recovering from the error is considered unsafe and could lead to further problems, such as memory leaks and hanging sockets. The appropriate use of the uncaughtException handler is to clean up any allocated resources, close connections, and log the error for later assessment before exiting the process.

// better
process.on('uncaughtException', (err) => {
  Honeybadger.notify(error); // log the error in a permanent storage
  // attempt a gracefully shutdown
  server.close(() => {
    process.exit(1); // then exit
  });

  // If a graceful shutdown is not achieved after 1 second,
  // shut down the process completely
  setTimeout(() => {
    process.abort(); // exit immediately and generate a core dump file
  }, 1000).unref()
});

Similarly, the unhandledRejection event is emitted when a rejected promise is not handled with a catch block. Unlike uncaughtException, these events do not cause the application to crash immediately. However, unhandled promise rejections have been deprecated and may terminate the process immediately in a future Node.js release. You can keep track of unhandled promise rejections through an unhandledRejection event listener, as shown below:

process.on('unhandledRejection', (reason, promise) => {
  Honeybadger.notify({
    message: 'Unhandled promise rejection',
    params: {
      promise,
      reason,
    },
  });
  server.close(() => {
    process.exit(1);
  });

  setTimeout(() => {
    process.abort();
  }, 1000).unref()
});

You should always run your servers using a process manager that will automatically restart them in the event of a crash. A common one is PM2, but you also have systemd or upstart on Linux, and Docker users can use its restart policy. Once this is in place, reliable service will be restored almost instantly, and you’ll still have the details of the uncaught exception so that it can be investigated and corrected promptly. You can go further by running more than one process and employ a load balancer to distribute incoming requests. This will help to prevent downtime in case one of the instances is lost temporarily.

Centralized error reporting

No error handling strategy is complete without a robust logging strategy for your running application. When a failure occurs, it’s important to learn why it happened by logging as much information as possible about the problem. Centralizing these logs makes it easy to get full visibility into your application. You’ll be able to sort and filter your errors, see top problems, and subscribe to alerts to get notified of new errors.

Honeybadger provides everything you need to monitor errors that occur in your production application. Follow the steps below to integrate it into your Node.js app:

1. Install the Package

Use npm to install the package:

$ npm install @honeybadger-io/js --save

2. Import the Library

Import the library and configure it with your API key to begin reporting errors:

const Honeybadger = require('@honeybadger-io/js');
Honeybadger.configure({
  apiKey: '[ YOUR API KEY HERE ]'
});

3. Report Errors

You can report an error by calling the notify() method, as shown in the following example:

try {
  // ...error producing code
} catch(error) {
  Honeybadger.notify(error);
}

For more information on how Honeybadger integrates with Node.js web frameworks, see the full documentation or check out the sample Node.js/Express application on GitHub.

Summary

The Error class (or a subclass) should always be used to communicate errors in your code. Technically, you can throw anything in JavaScript, not just Error objects, but this is not recommended since it greatly reduces the usefulness of the error and makes error handling error prone. By consistently using Error objects, you can reliably expect to access error.message or error.stack in places where the errors are being handled or logged. You can even augment the error class with other useful properties relevant to the context in which the error occurred.

Operational errors are unavoidable and should be accounted for in any correct program. Most of the time, a recoverable error strategy should be employed so that the program can continue running smoothly. However, if the error is severe enough, it might be appropriate to terminate the program and restart it. Try to shut down gracefully if such situations arise so that the program can start up again in a clean state.

Programmer errors cannot be handled or recovered from, but they can be mitigated with an automated test suite and static typing tools. When writing a function, define the behavior for bad parameters and act appropriately once detected. Allow the program to crash if an uncaughtException or unhandledRejection is detected. Don’t try to recover from such errors!

Use an error monitoring service, such as Honeybadger, to capture and analyze your errors. This can help you drastically improve the speed of debugging and resolution.

Conclusion

Proper error handling is a non-negotiable requirement if you’re aiming to write good and reliable software. By employing the techniques described in this article, you will be well on your way to doing just that.

Thanks for reading, and happy coding!

Пользовательские ошибки, расширение Error

Когда что-то разрабатываем, то нам часто необходимы собственные классы ошибок для разных вещей, которые могут пойти не так в наших задачах. Для ошибок при работе с сетью может понадобиться HttpError , для операций с базой данных DbError , для поиска – NotFoundError и т.д.

Наши ошибки должны поддерживать базовые свойства, такие как message , name и, желательно, stack . Но также они могут иметь свои собственные свойства. Например, объекты HttpError могут иметь свойство statusCode со значениями 404 , 403 или 500 .

JavaScript позволяет вызывать throw с любыми аргументами, то есть технически наши классы ошибок не нуждаются в наследовании от Error . Но если использовать наследование, то появляется возможность идентификации объектов ошибок посредством obj instanceof Error . Так что лучше применять наследование.

По мере роста приложения, наши собственные ошибки образуют иерархию, например, HttpTimeoutError может наследовать от HttpError и так далее.

Расширение Error

В качестве примера рассмотрим функцию readUser(json) , которая должна читать данные пользователя в формате JSON.

Пример того, как может выглядеть корректный json :

Внутри будем использовать JSON.parse . При получении некорректного json он будет генерировать ошибку SyntaxError . Но даже если json синтаксически верен, то это не значит, что это будет корректный пользователь, верно? Могут быть пропущены необходимые данные. Например, могут отсутствовать свойства name и age , которые являются необходимыми для наших пользователей.

Наша функция readUser(json) будет не только читать JSON-данные, но и проверять их («валидировать»). Если необходимые поля отсутствуют или данные в неверном формате, то это будет ошибкой. Но не синтаксической ошибкой SyntaxError , потому что данные синтаксически корректны. Это будет другая ошибка.

Назовём её ошибкой валидации ValidationError и создадим для неё класс. Ошибка этого вида должна содержать информацию о поле, которое является источником ошибки.

Наш класс ValidationError должен наследовать от встроенного класса Error .

Класс Error встроенный, вот его примерный код, просто чтобы мы понимали, что расширяем:

Теперь давайте унаследуем от него ValidationError и попробуем новый класс в действии:

Обратите внимание: в строке (1) вызываем родительский конструктор. JavaScript требует от нас вызова super в дочернем конструкторе, так что это обязательно. Родительский конструктор устанавливает свойство message .

Родительский конструктор также устанавливает свойство name для «Error» , поэтому в строке (2) мы сбрасываем его на правильное значение.

Попробуем использовать его в readUser(json) :

Блок try..catch в коде выше обрабатывает и нашу ValidationError , и встроенную SyntaxError из JSON.parse .

Обратите внимание, как мы используем instanceof для проверки конкретного типа ошибки в строке (*) .

Мы можем также проверить тип, используя err.name :

Версия с instanceof гораздо лучше, потому что в будущем мы собираемся расширить ValidationError , сделав его подтипы, такие как PropertyRequiredError . И проверка instanceof продолжит работать для новых наследованных классов. Так что это на будущее.

Также важно, что если catch встречает неизвестную ошибку, то он пробрасывает её в строке (**) . Блок catch знает, только как обрабатывать ошибки валидации и синтаксические ошибки, а другие виды ошибок (из-за опечаток в коде и другие непонятные) он должен выпустить наружу.

Дальнейшее наследование

Класс ValidationError является слишком общим. Много что может пойти не так. Свойство может отсутствовать или иметь неверный формат (например, строка как значение возраста age ). Поэтому для отсутствующих свойств сделаем более конкретный класс PropertyRequiredError . Он будет нести дополнительную информацию о свойстве, которое отсутствует.

Новый класс PropertyRequiredError очень просто использовать: необходимо указать только имя свойства new PropertyRequiredError(property) . Сообщение для пользователя message генерируется конструктором.

Обратите внимание, что свойство this.name в конструкторе PropertyRequiredError снова присвоено вручную. Правда, немного утомительно – присваивать this.name = в каждом классе пользовательской ошибки. Можно этого избежать, если сделать наш собственный «базовый» класс ошибки, который будет ставить this.name = this.constructor.name . И затем наследовать все ошибки уже от него.

Давайте назовём его MyError .

Вот упрощённый код с MyError и другими пользовательскими классами ошибок:

Теперь пользовательские ошибки стали намного короче, особенно ValidationError , так как мы избавились от строки «this.name = . » в конструкторе.

Обёртывание исключений

Назначение функции readUser в приведённом выше коде – это «чтение данных пользователя». В процессе могут возникнуть различные виды ошибок. Сейчас у нас есть SyntaxError и ValidationError , но в будущем функция readUser может расшириться и, возможно, генерировать другие виды ошибок.

Код, который вызывает readUser , должен обрабатывать эти ошибки.

Сейчас в нём используются проверки if в блоке catch , которые проверяют класс и обрабатывают известные ошибки и пробрасывают дальше неизвестные. Но если функция readUser генерирует несколько видов ошибок, то мы должны спросить себя: действительно ли мы хотим проверять все типы ошибок поодиночке во всех местах в коде, где вызывается readUser ?

Часто ответ «Нет»: внешний код хочет быть на один уровень выше всего этого. Он хочет иметь какую-то обобщённую ошибку чтения данных. Почему именно это произошло – часто не имеет значения (об этом говорится в сообщении об ошибке). Или даже лучше, если есть способ получить подробности об ошибке, но только если нам это нужно.

Итак, давайте создадим новый класс ReadError для представления таких ошибок. Если ошибка возникает внутри readUser , мы её перехватим и сгенерируем ReadError . Мы также сохраним ссылку на исходную ошибку в свойстве cause . Тогда внешний код должен будет только проверить наличие ReadError .

Этот код определяет ошибку ReadError и демонстрирует её использование в readUser и try..catch :

В приведённом выше коде readUser работает так, как описано – функция распознаёт синтаксические ошибки и ошибки валидации и выдаёт вместо них ошибки ReadError (неизвестные ошибки, как обычно, пробрасываются).

Внешний код проверяет только instanceof ReadError . Не нужно перечислять все возможные типы ошибок

Этот подход называется «обёртывание исключений», потому что мы берём «исключения низкого уровня» и «оборачиваем» их в ReadError , который является более абстрактным и более удобным для использования в вызывающем коде. Такой подход широко используется в объектно-ориентированном программировании.

Итого

  • Мы можем наследовать свои классы ошибок от Error и других встроенных классов ошибок, но нужно позаботиться о свойстве name и не забыть вызвать super .
  • Мы можем использовать instanceof для проверки типа ошибок. Это также работает с наследованием. Но иногда у нас объект ошибки, возникшей в сторонней библиотеке, и нет простого способа получить класс. Тогда для проверки типа ошибки можно использовать свойство name .
  • Обёртывание исключений является распространённой техникой: функция ловит низкоуровневые исключения и создаёт одно «высокоуровневое» исключение вместо разных низкоуровневых. Иногда низкоуровневые исключения становятся свойствами этого объекта, как err.cause в примерах выше, но это не обязательно.

Задачи

Наследование от SyntaxError

Создайте класс FormatError , который наследует от встроенного класса SyntaxError .

Класс должен поддерживать свойства message , name и stack .

Источник

Node.js v19.4.0 documentation

Errors #

Applications running in Node.js will generally experience four categories of errors:

  • Standard JavaScript errors such as , , , , , and .
  • System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist or attempting to send data over a closed socket.
  • User-specified errors triggered by application code.
  • AssertionError s are a special class of error that can be triggered when Node.js detects an exceptional logic violation that should never occur. These are raised typically by the node:assert module.

All JavaScript and system errors raised by Node.js inherit from, or are instances of, the standard JavaScript class and are guaranteed to provide at least the properties available on that class.

Error propagation and interception #

Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and handled depends entirely on the type of Error and the style of the API that is called.

All JavaScript errors are handled as exceptions that immediately generate and throw an error using the standard JavaScript throw mechanism. These are handled using the try…catch construct provided by the JavaScript language.

Any use of the JavaScript throw mechanism will raise an exception that must be handled using try…catch or the Node.js process will exit immediately.

With few exceptions, Synchronous APIs (any blocking method that does not accept a callback function, such as fs.readFileSync ), will use throw to report errors.

Errors that occur within Asynchronous APIs may be reported in multiple ways:

Most asynchronous methods that accept a callback function will accept an Error object passed as the first argument to that function. If that first argument is not null and is an instance of Error , then an error occurred that should be handled.

When an asynchronous method is called on an object that is an EventEmitter , errors can be routed to that object’s ‘error’ event.

A handful of typically asynchronous methods in the Node.js API may still use the throw mechanism to raise exceptions that must be handled using try…catch . There is no comprehensive list of such methods; please refer to the documentation of each method to determine the appropriate error handling mechanism required.

The use of the ‘error’ event mechanism is most common for stream-based and event emitter-based APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail).

For all EventEmitter objects, if an ‘error’ event handler is not provided, the error will be thrown, causing the Node.js process to report an uncaught exception and crash unless either: The domain module is used appropriately or a handler has been registered for the ‘uncaughtException’ event.

Errors generated in this way cannot be intercepted using try…catch as they are thrown after the calling code has already exited.

Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated.

Error-first callbacks #

Most asynchronous methods exposed by the Node.js core API follow an idiomatic pattern referred to as an error-first callback. With this pattern, a callback function is passed to the method as an argument. When the operation either completes or an error is raised, the callback function is called with the Error object (if any) passed as the first argument. If no error was raised, the first argument will be passed as null .

The JavaScript try…catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside an error-first callback:

This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code, including the try…catch block, will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with process.on(‘uncaughtException’) , such errors can be intercepted.

Class: Error #

A generic JavaScript object that does not denote any specific circumstance of why the error occurred. Error objects capture a «stack trace» detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.

All errors generated by Node.js, including all system and JavaScript errors, will either be instances of, or inherit from, the Error class.

new Error(message[, options]) #

Creates a new Error object and sets the error.message property to the provided text message. If an object is passed as message , the text message is generated by calling String(message) . If the cause option is provided, it is assigned to the error.cause property. The error.stack property will represent the point in the code at which new Error() was called. Stack traces are dependent on V8’s stack trace API. Stack traces extend only to either (a) the beginning of synchronous code execution, or (b) the number of frames given by the property Error.stackTraceLimit , whichever is smaller.

Error.captureStackTrace(targetObject[, constructorOpt]) #

Creates a .stack property on targetObject , which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

The first line of the trace will be prefixed with $: $ .

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt , including constructorOpt , will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

Error.stackTraceLimit #

The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj) ).

The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

error.cause #

If present, the error.cause property is the underlying cause of the Error . It is used when catching an error and throwing a new one with a different message or code in order to still have access to the original error.

The error.cause property is typically set by calling new Error(message, < cause >) . It is not set by the constructor if the cause option is not provided.

This property allows errors to be chained. When serializing Error objects, util.inspect() recursively serializes error.cause if it is set.

error.code #

The error.code property is a string label that identifies the kind of error. error.code is the most stable way to identify an error. It will only change between major versions of Node.js. In contrast, error.message strings may change between any versions of Node.js. See Node.js error codes for details about specific codes.

error.message #

The error.message property is the string description of the error as set by calling new Error(message) . The message passed to the constructor will also appear in the first line of the stack trace of the Error , however changing this property after the Error object is created may not change the first line of the stack trace (for example, when error.stack is read before this property is changed).

error.stack #

The error.stack property is a string describing the point in the code at which the Error was instantiated.

The first line is formatted as : , and is followed by a series of stack frames (each line beginning with «at «). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses.

Frames are only generated for JavaScript functions. If, for example, execution synchronously passes through a C++ addon function called cheetahify which itself calls a JavaScript function, the frame representing the cheetahify call will not be present in the stack traces:

The location information will be one of:

  • native , if the frame represents a call internal to V8 (as in [].forEach ).
  • plain-filename.js:line:column , if the frame represents a call internal to Node.js.
  • /absolute/path/to/file.js:line:column , if the frame represents a call in a user program (using CommonJS module system), or its dependencies.
  • :///url/to/module/file.mjs:line:column , if the frame represents a call in a user program (using ES module system), or its dependencies.

The string representing the stack trace is lazily generated when the error.stack property is accessed.

The number of frames captured by the stack trace is bounded by the smaller of Error.stackTraceLimit or the number of available frames on the current event loop tick.

Class: AssertionError #

Indicates the failure of an assertion. For details, see Class: assert.AssertionError .

Class: RangeError #

Indicates that a provided argument was not within the set or range of acceptable values for a function; whether that is a numeric range, or outside the set of options for a given function parameter.

Node.js will generate and throw RangeError instances immediately as a form of argument validation.

Class: ReferenceError #

Indicates that an attempt is being made to access a variable that is not defined. Such errors commonly indicate typos in code, or an otherwise broken program.

While client code may generate and propagate these errors, in practice, only V8 will do so.

Unless an application is dynamically generating and running code, ReferenceError instances indicate a bug in the code or its dependencies.

Class: SyntaxError #

Indicates that a program is not valid JavaScript. These errors may only be generated and propagated as a result of code evaluation. Code evaluation may happen as a result of eval , Function , require , or vm. These errors are almost always indicative of a broken program.

SyntaxError instances are unrecoverable in the context that created them – they may only be caught by other contexts.

Class: SystemError #

Node.js generates system errors when exceptions occur within its runtime environment. These usually occur when an application violates an operating system constraint. For example, a system error will occur if an application attempts to read a file that does not exist.

  • address If present, the address to which a network connection failed
  • code The string error code
  • dest If present, the file path destination when reporting a file system error
  • errno The system-provided error number
  • info If present, extra details about the error condition
  • message A system-provided human-readable description of the error
  • path If present, the file path when reporting a file system error
  • port If present, the network connection port that is not available
  • syscall The name of the system call that triggered the error

error.address #

If present, error.address is a string describing the address to which a network connection failed.

error.code #

The error.code property is a string representing the error code.

error.dest #

If present, error.dest is the file path destination when reporting a file system error.

error.errno #

The error.errno property is a negative number which corresponds to the error code defined in libuv Error handling .

On Windows the error number provided by the system will be normalized by libuv.

To get the string representation of the error code, use util.getSystemErrorName(error.errno) .

error.info #

If present, error.info is an object with details about the error condition.

error.message #

error.message is a system-provided human-readable description of the error.

error.path #

If present, error.path is a string containing a relevant invalid pathname.

error.port #

If present, error.port is the network connection port that is not available.

error.syscall #

The error.syscall property is a string describing the syscall that failed.

Common system errors #

This is a list of system errors commonly-encountered when writing a Node.js program. For a comprehensive list, see the errno (3) man page.

EACCES (Permission denied): An attempt was made to access a file in a way forbidden by its file access permissions.

EADDRINUSE (Address already in use): An attempt to bind a server ( net , http , or https ) to a local address failed due to another server on the local system already occupying that address.

ECONNREFUSED (Connection refused): No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host.

ECONNRESET (Connection reset by peer): A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot. Commonly encountered via the http and net modules.

EEXIST (File exists): An existing file was the target of an operation that required that the target not exist.

EISDIR (Is a directory): An operation expected a file, but the given pathname was a directory.

EMFILE (Too many open files in system): Maximum number of file descriptors allowable on the system has been reached, and requests for another descriptor cannot be fulfilled until at least one has been closed. This is encountered when opening many files at once in parallel, especially on systems (in particular, macOS) where there is a low file descriptor limit for processes. To remedy a low limit, run ulimit -n 2048 in the same shell that will run the Node.js process.

ENOENT (No such file or directory): Commonly raised by fs operations to indicate that a component of the specified pathname does not exist. No entity (file or directory) could be found by the given path.

ENOTDIR (Not a directory): A component of the given pathname existed, but was not a directory as expected. Commonly raised by fs.readdir .

ENOTEMPTY (Directory not empty): A directory with entries was the target of an operation that requires an empty directory, usually fs.unlink .

ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either EAI_NODATA or EAI_NONAME . This is not a standard POSIX error.

EPERM (Operation not permitted): An attempt was made to perform an operation that requires elevated privileges.

EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is no process to read the data. Commonly encountered at the net and http layers, indicative that the remote side of the stream being written to has been closed.

ETIMEDOUT (Operation timed out): A connect or send request failed because the connected party did not properly respond after a period of time. Usually encountered by http or net . Often a sign that a socket.end() was not properly called.

Class: TypeError #

Indicates that a provided argument is not an allowable type. For example, passing a function to a parameter which expects a string would be a TypeError .

Node.js will generate and throw TypeError instances immediately as a form of argument validation.

Exceptions vs. errors #

A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a throw statement. While it is not required that these values are instances of Error or classes which inherit from Error , all exceptions thrown by Node.js or the JavaScript runtime will be instances of Error .

Some exceptions are unrecoverable at the JavaScript layer. Such exceptions will always cause the Node.js process to crash. Examples include assert() checks or abort() calls in the C++ layer.

OpenSSL errors #

Errors originating in crypto or tls are of class Error , and in addition to the standard .code and .message properties, may have some additional OpenSSL-specific properties.

error.opensslErrorStack #

An array of errors that can give context to where in the OpenSSL library an error originates from.

error.function #

The OpenSSL function the error originates in.

error.library #

The OpenSSL library the error originates in.

error.reason #

A human-readable string describing the reason for the error.

Node.js error codes #

ABORT_ERR #

Used when an operation has been aborted (typically using an AbortController ).

APIs not using AbortSignal s typically do not raise an error with this code.

This code does not use the regular ERR_* convention Node.js errors use in order to be compatible with the web platform’s AbortError .

ERR_AMBIGUOUS_ARGUMENT #

A function argument is being used in a way that suggests that the function signature may be misunderstood. This is thrown by the node:assert module when the message parameter in assert.throws(block, message) matches the error message thrown by block because that usage suggests that the user believes message is the expected message rather than the message the AssertionError will display if block does not throw.

ERR_ARG_NOT_ITERABLE #

An iterable argument (i.e. a value that works with for. of loops) was required, but not provided to a Node.js API.

ERR_ASSERTION #

A special type of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the node:assert module.

ERR_ASSERT_SNAPSHOT_NOT_SUPPORTED #

An attempt was made to use assert.snapshot() in an environment that does not support snapshots, such as the REPL, or when using node —eval .

ERR_ASYNC_CALLBACK #

An attempt was made to register something that is not a function as an AsyncHooks callback.

ERR_ASYNC_TYPE #

The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API.

ERR_BROTLI_COMPRESSION_FAILED #

Data passed to a Brotli stream was not successfully compressed.

ERR_BROTLI_INVALID_PARAM #

An invalid parameter key was passed during construction of a Brotli stream.

ERR_BUFFER_CONTEXT_NOT_AVAILABLE #

An attempt was made to create a Node.js Buffer instance from addon or embedder code, while in a JS engine Context that is not associated with a Node.js instance. The data passed to the Buffer method will have been released by the time the method returns.

When encountering this error, a possible alternative to creating a Buffer instance is to create a normal Uint8Array , which only differs in the prototype of the resulting object. Uint8Array s are generally accepted in all Node.js core APIs where Buffer s are; they are available in all Contexts.

ERR_BUFFER_OUT_OF_BOUNDS #

An operation outside the bounds of a Buffer was attempted.

ERR_BUFFER_TOO_LARGE #

An attempt has been made to create a Buffer larger than the maximum allowed size.

ERR_CANNOT_WATCH_SIGINT #

Node.js was unable to watch for the SIGINT signal.

ERR_CHILD_CLOSED_BEFORE_REPLY #

A child process was closed before the parent received a reply.

ERR_CHILD_PROCESS_IPC_REQUIRED #

Used when a child process is being forked without specifying an IPC channel.

ERR_CHILD_PROCESS_STDIO_MAXBUFFER #

Used when the main process is trying to read data from the child process’s STDERR/STDOUT, and the data’s length is longer than the maxBuffer option.

ERR_CLOSED_MESSAGE_PORT #

There was an attempt to use a MessagePort instance in a closed state, usually after .close() has been called.

ERR_CONSOLE_WRITABLE_STREAM #

Console was instantiated without stdout stream, or Console has a non-writable stdout or stderr stream.

ERR_CONSTRUCT_CALL_INVALID #

A class constructor was called that is not callable.

ERR_CONSTRUCT_CALL_REQUIRED #

A constructor for a class was called without new .

ERR_CONTEXT_NOT_INITIALIZED #

The vm context passed into the API is not yet initialized. This could happen when an error occurs (and is caught) during the creation of the context, for example, when the allocation fails or the maximum call stack size is reached when the context is created.

ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED #

A client certificate engine was requested that is not supported by the version of OpenSSL being used.

ERR_CRYPTO_ECDH_INVALID_FORMAT #

An invalid value for the format argument was passed to the crypto.ECDH() class getPublicKey() method.

ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY #

An invalid value for the key argument has been passed to the crypto.ECDH() class computeSecret() method. It means that the public key lies outside of the elliptic curve.

ERR_CRYPTO_ENGINE_UNKNOWN #

An invalid crypto engine identifier was passed to require(‘node:crypto’).setEngine() .

ERR_CRYPTO_FIPS_FORCED #

The —force-fips command-line argument was used but there was an attempt to enable or disable FIPS mode in the node:crypto module.

ERR_CRYPTO_FIPS_UNAVAILABLE #

An attempt was made to enable or disable FIPS mode, but FIPS mode was not available.

ERR_CRYPTO_HASH_FINALIZED #

hash.digest() was called multiple times. The hash.digest() method must be called no more than one time per instance of a Hash object.

ERR_CRYPTO_HASH_UPDATE_FAILED #

hash.update() failed for any reason. This should rarely, if ever, happen.

ERR_CRYPTO_INCOMPATIBLE_KEY #

The given crypto keys are incompatible with the attempted operation.

ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS #

The selected public or private key encoding is incompatible with other options.

ERR_CRYPTO_INITIALIZATION_FAILED #

Initialization of the crypto subsystem failed.

ERR_CRYPTO_INVALID_AUTH_TAG #

An invalid authentication tag was provided.

ERR_CRYPTO_INVALID_COUNTER #

An invalid counter was provided for a counter-mode cipher.

ERR_CRYPTO_INVALID_CURVE #

An invalid elliptic-curve was provided.

ERR_CRYPTO_INVALID_DIGEST #

An invalid crypto digest algorithm was specified.

ERR_CRYPTO_INVALID_IV #

An invalid initialization vector was provided.

ERR_CRYPTO_INVALID_JWK #

An invalid JSON Web Key was provided.

ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE #

The given crypto key object’s type is invalid for the attempted operation.

ERR_CRYPTO_INVALID_KEYLEN #

An invalid key length was provided.

ERR_CRYPTO_INVALID_KEYPAIR #

An invalid key pair was provided.

ERR_CRYPTO_INVALID_KEYTYPE #

An invalid key type was provided.

ERR_CRYPTO_INVALID_MESSAGELEN #

An invalid message length was provided.

ERR_CRYPTO_INVALID_SCRYPT_PARAMS #

Invalid scrypt algorithm parameters were provided.

ERR_CRYPTO_INVALID_STATE #

A crypto method was used on an object that was in an invalid state. For instance, calling cipher.getAuthTag() before calling cipher.final() .

ERR_CRYPTO_INVALID_TAG_LENGTH #

An invalid authentication tag length was provided.

ERR_CRYPTO_JOB_INIT_FAILED #

Initialization of an asynchronous crypto operation failed.

ERR_CRYPTO_JWK_UNSUPPORTED_CURVE #

Key’s Elliptic Curve is not registered for use in the JSON Web Key Elliptic Curve Registry.

ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE #

Key’s Asymmetric Key Type is not registered for use in the JSON Web Key Types Registry.

ERR_CRYPTO_OPERATION_FAILED #

A crypto operation failed for an otherwise unspecified reason.

ERR_CRYPTO_PBKDF2_ERROR #

The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js.

ERR_CRYPTO_SCRYPT_INVALID_PARAMETER #

One or more crypto.scrypt() or crypto.scryptSync() parameters are outside their legal range.

ERR_CRYPTO_SCRYPT_NOT_SUPPORTED #

Node.js was compiled without scrypt support. Not possible with the official release binaries but can happen with custom builds, including distro builds.

ERR_CRYPTO_SIGN_KEY_REQUIRED #

A signing key was not provided to the sign.sign() method.

ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH #

crypto.timingSafeEqual() was called with Buffer , TypedArray , or DataView arguments of different lengths.

ERR_CRYPTO_UNKNOWN_CIPHER #

An unknown cipher was specified.

ERR_CRYPTO_UNKNOWN_DH_GROUP #

An unknown Diffie-Hellman group name was given. See crypto.getDiffieHellman() for a list of valid group names.

ERR_CRYPTO_UNSUPPORTED_OPERATION #

An attempt to invoke an unsupported crypto operation was made.

ERR_DEBUGGER_ERROR #

An error occurred with the debugger.

ERR_DEBUGGER_STARTUP_ERROR #

The debugger timed out waiting for the required host/port to be free.

ERR_DLOPEN_DISABLED #

Loading native addons has been disabled using —no-addons .

ERR_DLOPEN_FAILED #

A call to process.dlopen() failed.

ERR_DIR_CLOSED #

The fs.Dir was previously closed.

ERR_DIR_CONCURRENT_OPERATION #

A synchronous read or close call was attempted on an fs.Dir which has ongoing asynchronous operations.

ERR_DNS_SET_SERVERS_FAILED #

c-ares failed to set the DNS server.

ERR_DOMAIN_CALLBACK_NOT_AVAILABLE #

The node:domain module was not usable since it could not establish the required error handling hooks, because process.setUncaughtExceptionCaptureCallback() had been called at an earlier point in time.

ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE #

process.setUncaughtExceptionCaptureCallback() could not be called because the node:domain module has been loaded at an earlier point in time.

The stack trace is extended to include the point in time at which the node:domain module had been loaded.

ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION #

v8.startupSnapshot.setDeserializeMainFunction() could not be called because it had already been called before.

ERR_ENCODING_INVALID_ENCODED_DATA #

Data provided to TextDecoder() API was invalid according to the encoding provided.

ERR_ENCODING_NOT_SUPPORTED #

Encoding provided to TextDecoder() API was not one of the WHATWG Supported Encodings.

ERR_EVAL_ESM_CANNOT_PRINT #

—print cannot be used with ESM input.

ERR_EVENT_RECURSION #

Thrown when an attempt is made to recursively dispatch an event on EventTarget .

ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE #

The JS execution context is not associated with a Node.js environment. This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly.

ERR_FALSY_VALUE_REJECTION #

A Promise that was callbackified via util.callbackify() was rejected with a falsy value.

ERR_FEATURE_UNAVAILABLE_ON_PLATFORM #

Used when a feature that is not available to the current platform which is running Node.js is used.

ERR_FS_CP_DIR_TO_NON_DIR #

An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using fs.cp() .

ERR_FS_CP_EEXIST #

An attempt was made to copy over a file that already existed with fs.cp() , with the force and errorOnExist set to true .

ERR_FS_CP_EINVAL #

When using fs.cp() , src or dest pointed to an invalid path.

ERR_HTTP_CONTENT_LENGTH_MISMATCH #

Response body size doesn’t match with the specified content-length header value.

ERR_FS_CP_FIFO_PIPE #

An attempt was made to copy a named pipe with fs.cp() .

ERR_FS_CP_NON_DIR_TO_DIR #

An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using fs.cp() .

ERR_FS_CP_SOCKET #

An attempt was made to copy to a socket with fs.cp() .

ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY #

When using fs.cp() , a symlink in dest pointed to a subdirectory of src .

ERR_FS_CP_UNKNOWN #

An attempt was made to copy to an unknown file type with fs.cp() .

ERR_FS_EISDIR #

Path is a directory.

ERR_FS_FILE_TOO_LARGE #

An attempt has been made to read a file whose size is larger than the maximum allowed size for a Buffer .

ERR_FS_INVALID_SYMLINK_TYPE #

An invalid symlink type was passed to the fs.symlink() or fs.symlinkSync() methods.

ERR_HTTP_HEADERS_SENT #

An attempt was made to add more headers after the headers had already been sent.

ERR_HTTP_INVALID_HEADER_VALUE #

An invalid HTTP header value was specified.

ERR_HTTP_INVALID_STATUS_CODE #

Status code was outside the regular status code range (100-999).

ERR_HTTP_REQUEST_TIMEOUT #

The client has not sent the entire request within the allowed time.

ERR_HTTP_SOCKET_ENCODING #

Changing the socket encoding is not allowed per RFC 7230 Section 3.

ERR_HTTP_TRAILER_INVALID #

The Trailer header was set even though the transfer encoding does not support that.

ERR_HTTP2_ALTSVC_INVALID_ORIGIN #

HTTP/2 ALTSVC frames require a valid origin.

ERR_HTTP2_ALTSVC_LENGTH #

HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.

ERR_HTTP2_CONNECT_AUTHORITY #

For HTTP/2 requests using the CONNECT method, the :authority pseudo-header is required.

ERR_HTTP2_CONNECT_PATH #

For HTTP/2 requests using the CONNECT method, the :path pseudo-header is forbidden.

ERR_HTTP2_CONNECT_SCHEME #

For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is forbidden.

ERR_HTTP2_ERROR #

A non-specific HTTP/2 error has occurred.

ERR_HTTP2_GOAWAY_SESSION #

New HTTP/2 Streams may not be opened after the Http2Session has received a GOAWAY frame from the connected peer.

ERR_HTTP2_HEADER_SINGLE_VALUE #

Multiple values were provided for an HTTP/2 header field that was required to have only a single value.

ERR_HTTP2_HEADERS_AFTER_RESPOND #

An additional headers was specified after an HTTP/2 response was initiated.

ERR_HTTP2_HEADERS_SENT #

An attempt was made to send multiple response headers.

ERR_HTTP2_INFO_STATUS_NOT_ALLOWED #

Informational HTTP status codes ( 1xx ) may not be set as the response status code on HTTP/2 responses.

ERR_HTTP2_INVALID_CONNECTION_HEADERS #

HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses.

ERR_HTTP2_INVALID_HEADER_VALUE #

An invalid HTTP/2 header value was specified.

ERR_HTTP2_INVALID_INFO_STATUS #

An invalid HTTP informational status code has been specified. Informational status codes must be an integer between 100 and 199 (inclusive).

ERR_HTTP2_INVALID_ORIGIN #

HTTP/2 ORIGIN frames require a valid origin.

ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH #

Input Buffer and Uint8Array instances passed to the http2.getUnpackedSettings() API must have a length that is a multiple of six.

ERR_HTTP2_INVALID_PSEUDOHEADER #

Only valid HTTP/2 pseudoheaders ( :status , :path , :authority , :scheme , and :method ) may be used.

ERR_HTTP2_INVALID_SESSION #

An action was performed on an Http2Session object that had already been destroyed.

ERR_HTTP2_INVALID_SETTING_VALUE #

An invalid value has been specified for an HTTP/2 setting.

ERR_HTTP2_INVALID_STREAM #

An operation was performed on a stream that had already been destroyed.

ERR_HTTP2_MAX_PENDING_SETTINGS_ACK #

Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new SETTINGS . By default, a maximum number of unacknowledged SETTINGS frames may be sent at any given time. This error code is used when that limit has been reached.

ERR_HTTP2_NESTED_PUSH #

An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted.

ERR_HTTP2_NO_MEM #

Out of memory when using the http2session.setLocalWindowSize(windowSize) API.

ERR_HTTP2_NO_SOCKET_MANIPULATION #

An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an Http2Session .

ERR_HTTP2_ORIGIN_LENGTH #

HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.

ERR_HTTP2_OUT_OF_STREAMS #

The number of streams created on a single HTTP/2 session reached the maximum limit.

ERR_HTTP2_PAYLOAD_FORBIDDEN #

A message payload was specified for an HTTP response code for which a payload is forbidden.

ERR_HTTP2_PING_CANCEL #

An HTTP/2 ping was canceled.

ERR_HTTP2_PING_LENGTH #

HTTP/2 ping payloads must be exactly 8 bytes in length.

ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED #

An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the : prefix.

ERR_HTTP2_PUSH_DISABLED #

An attempt was made to create a push stream, which had been disabled by the client.

ERR_HTTP2_SEND_FILE #

An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send a directory.

ERR_HTTP2_SEND_FILE_NOSEEK #

An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send something other than a regular file, but offset or length options were provided.

ERR_HTTP2_SESSION_ERROR #

The Http2Session closed with a non-zero error code.

ERR_HTTP2_SETTINGS_CANCEL #

The Http2Session settings canceled.

ERR_HTTP2_SOCKET_BOUND #

An attempt was made to connect a Http2Session object to a net.Socket or tls.TLSSocket that had already been bound to another Http2Session object.

ERR_HTTP2_SOCKET_UNBOUND #

An attempt was made to use the socket property of an Http2Session that has already been closed.

ERR_HTTP2_STATUS_101 #

Use of the 101 Informational status code is forbidden in HTTP/2.

ERR_HTTP2_STATUS_INVALID #

An invalid HTTP status code has been specified. Status codes must be an integer between 100 and 599 (inclusive).

ERR_HTTP2_STREAM_CANCEL #

An Http2Stream was destroyed before any data was transmitted to the connected peer.

ERR_HTTP2_STREAM_ERROR #

A non-zero error code was been specified in an RST_STREAM frame.

ERR_HTTP2_STREAM_SELF_DEPENDENCY #

When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself.

ERR_HTTP2_TOO_MANY_INVALID_FRAMES #

The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the maxSessionInvalidFrames option, has been exceeded.

ERR_HTTP2_TRAILERS_ALREADY_SENT #

Trailing headers have already been sent on the Http2Stream .

ERR_HTTP2_TRAILERS_NOT_READY #

The http2stream.sendTrailers() method cannot be called until after the ‘wantTrailers’ event is emitted on an Http2Stream object. The ‘wantTrailers’ event will only be emitted if the waitForTrailers option is set for the Http2Stream .

ERR_HTTP2_UNSUPPORTED_PROTOCOL #

http2.connect() was passed a URL that uses any protocol other than http: or https: .

ERR_ILLEGAL_CONSTRUCTOR #

An attempt was made to construct an object using a non-public constructor.

ERR_IMPORT_ASSERTION_TYPE_FAILED #

An import assertion has failed, preventing the specified module to be imported.

ERR_IMPORT_ASSERTION_TYPE_MISSING #

An import assertion is missing, preventing the specified module to be imported.

ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED #

An import assertion is not supported by this version of Node.js.

ERR_INCOMPATIBLE_OPTION_PAIR #

An option pair is incompatible with each other and cannot be used at the same time.

ERR_INPUT_TYPE_NOT_ALLOWED #

The —input-type flag was used to attempt to execute a file. This flag can only be used with input via —eval , —print , or STDIN .

ERR_INSPECTOR_ALREADY_ACTIVATED #

While using the node:inspector module, an attempt was made to activate the inspector when it already started to listen on a port. Use inspector.close() before activating it on a different address.

ERR_INSPECTOR_ALREADY_CONNECTED #

While using the node:inspector module, an attempt was made to connect when the inspector was already connected.

ERR_INSPECTOR_CLOSED #

While using the node:inspector module, an attempt was made to use the inspector after the session had already closed.

ERR_INSPECTOR_COMMAND #

An error occurred while issuing a command via the node:inspector module.

ERR_INSPECTOR_NOT_ACTIVE #

The inspector is not active when inspector.waitForDebugger() is called.

ERR_INSPECTOR_NOT_AVAILABLE #

The node:inspector module is not available for use.

ERR_INSPECTOR_NOT_CONNECTED #

While using the node:inspector module, an attempt was made to use the inspector before it was connected.

ERR_INSPECTOR_NOT_WORKER #

An API was called on the main thread that can only be used from the worker thread.

ERR_INTERNAL_ASSERTION #

There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at https://github.com/nodejs/node/issues.

ERR_INVALID_ADDRESS_FAMILY #

The provided address family is not understood by the Node.js API.

ERR_INVALID_ARG_TYPE #

An argument of the wrong type was passed to a Node.js API.

ERR_INVALID_ARG_VALUE #

An invalid or unsupported value was passed for a given argument.

ERR_INVALID_ASYNC_ID #

An invalid asyncId or triggerAsyncId was passed using AsyncHooks . An id less than -1 should never happen.

ERR_INVALID_BUFFER_SIZE #

A swap was performed on a Buffer but its size was not compatible with the operation.

ERR_INVALID_CHAR #

Invalid characters were detected in headers.

ERR_INVALID_CURSOR_POS #

A cursor on a given stream cannot be moved to a specified row without a specified column.

ERR_INVALID_FD #

A file descriptor (‘fd’) was not valid (e.g. it was a negative value).

ERR_INVALID_FD_TYPE #

A file descriptor (‘fd’) type was not valid.

ERR_INVALID_FILE_URL_HOST #

A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible host. This situation can only occur on Unix-like systems where only localhost or an empty host is supported.

ERR_INVALID_FILE_URL_PATH #

A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible path. The exact semantics for determining whether a path can be used is platform-dependent.

ERR_INVALID_HANDLE_TYPE #

An attempt was made to send an unsupported «handle» over an IPC communication channel to a child process. See subprocess.send() and process.send() for more information.

ERR_INVALID_HTTP_TOKEN #

An invalid HTTP token was supplied.

ERR_INVALID_IP_ADDRESS #

An IP address is not valid.

ERR_INVALID_MIME_SYNTAX #

The syntax of a MIME is not valid.

ERR_INVALID_MODULE #

An attempt was made to load a module that does not exist or was otherwise not valid.

ERR_INVALID_MODULE_SPECIFIER #

The imported module string is an invalid URL, package name, or package subpath specifier.

ERR_INVALID_OBJECT_DEFINE_PROPERTY #

An error occurred while setting an invalid attribute on the property of an object.

ERR_INVALID_PACKAGE_CONFIG #

An invalid package.json file failed parsing.

ERR_INVALID_PACKAGE_TARGET #

The package.json «exports» field contains an invalid target mapping value for the attempted module resolution.

ERR_INVALID_PERFORMANCE_MARK #

While using the Performance Timing API ( perf_hooks ), a performance mark is invalid.

ERR_INVALID_PROTOCOL #

An invalid options.protocol was passed to http.request() .

ERR_INVALID_REPL_EVAL_CONFIG #

Both breakEvalOnSigint and eval options were set in the REPL config, which is not supported.

ERR_INVALID_REPL_INPUT #

The input may not be used in the REPL . The conditions under which this error is used are described in the REPL documentation.

ERR_INVALID_RETURN_PROPERTY #

Thrown in case a function option does not provide a valid value for one of its returned object properties on execution.

ERR_INVALID_RETURN_PROPERTY_VALUE #

Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution.

ERR_INVALID_RETURN_VALUE #

Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise.

ERR_INVALID_STATE #

Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be performing another operation.

ERR_INVALID_SYNC_FORK_INPUT #

A Buffer , TypedArray , DataView , or string was provided as stdio input to an asynchronous fork. See the documentation for the child_process module for more information.

ERR_INVALID_THIS #

A Node.js API function was called with an incompatible this value.

ERR_INVALID_TRANSFER_OBJECT #

An invalid transfer object was passed to postMessage() .

ERR_INVALID_TUPLE #

An element in the iterable provided to the WHATWG URLSearchParams constructor did not represent a [name, value] tuple – that is, if an element is not iterable, or does not consist of exactly two elements.

ERR_INVALID_URI #

An invalid URI was passed.

ERR_INVALID_URL #

An invalid URL was passed to the WHATWG URL constructor or the legacy url.parse() to be parsed. The thrown error object typically has an additional property ‘input’ that contains the URL that failed to parse.

ERR_INVALID_URL_SCHEME #

An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the WHATWG URL API support in the fs module (which only accepts URLs with ‘file’ scheme), but may be used in other Node.js APIs as well in the future.

ERR_IPC_CHANNEL_CLOSED #

An attempt was made to use an IPC communication channel that was already closed.

ERR_IPC_DISCONNECTED #

An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the child_process module for more information.

ERR_IPC_ONE_PIPE #

An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the child_process module for more information.

ERR_IPC_SYNC_FORK #

An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the child_process module for more information.

ERR_LOADER_CHAIN_INCOMPLETE #

An ESM loader hook returned without calling next() and without explicitly signaling a short circuit.

ERR_MANIFEST_ASSERT_INTEGRITY #

An attempt was made to load a resource, but the resource did not match the integrity defined by the policy manifest. See the documentation for policy manifests for more information.

ERR_MANIFEST_DEPENDENCY_MISSING #

An attempt was made to load a resource, but the resource was not listed as a dependency from the location that attempted to load it. See the documentation for policy manifests for more information.

ERR_MANIFEST_INTEGRITY_MISMATCH #

An attempt was made to load a policy manifest, but the manifest had multiple entries for a resource which did not match each other. Update the manifest entries to match in order to resolve this error. See the documentation for policy manifests for more information.

ERR_MANIFEST_INVALID_RESOURCE_FIELD #

A policy manifest resource had an invalid value for one of its fields. Update the manifest entry to match in order to resolve this error. See the documentation for policy manifests for more information.

ERR_MANIFEST_INVALID_SPECIFIER #

A policy manifest resource had an invalid value for one of its dependency mappings. Update the manifest entry to match to resolve this error. See the documentation for policy manifests for more information.

ERR_MANIFEST_PARSE_POLICY #

An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for policy manifests for more information.

ERR_MANIFEST_TDZ #

An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js.

ERR_MANIFEST_UNKNOWN_ONERROR #

A policy manifest was loaded, but had an unknown value for its «onerror» behavior. See the documentation for policy manifests for more information.

ERR_MEMORY_ALLOCATION_FAILED #

An attempt was made to allocate memory (usually in the C++ layer) but it failed.

ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE #

A message posted to a MessagePort could not be deserialized in the target vm Context . Not all Node.js objects can be successfully instantiated in any context at this time, and attempting to transfer them using postMessage() can fail on the receiving side in that case.

ERR_METHOD_NOT_IMPLEMENTED #

A method is required but not implemented.

ERR_MISSING_ARGS #

A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept func(undefined) but not func() ). In most native Node.js APIs, func(undefined) and func() are treated identically, and the ERR_INVALID_ARG_TYPE error code may be used instead.

ERR_MISSING_OPTION #

For APIs that accept options objects, some options might be mandatory. This code is thrown if a required option is missing.

ERR_MISSING_PASSPHRASE #

An attempt was made to read an encrypted key without specifying a passphrase.

ERR_MISSING_PLATFORM_FOR_WORKER #

The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js.

ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST #

An object that needs to be explicitly listed in the transferList argument is in the object passed to a postMessage() call, but is not provided in the transferList for that call. Usually, this is a MessagePort .

In Node.js versions prior to v15.0.0, the error code being used here was ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST . However, the set of transferable object types has been expanded to cover more types than MessagePort .

ERR_MODULE_NOT_FOUND #

A module file could not be resolved by the ECMAScript modules loader while attempting an import operation or when loading the program entry point.

ERR_MULTIPLE_CALLBACK #

A callback was called more than once.

A callback is almost always meant to only be called once as the query can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once.

ERR_NAPI_CONS_FUNCTION #

While using Node-API , a constructor passed was not a function.

ERR_NAPI_INVALID_DATAVIEW_ARGS #

While calling napi_create_dataview() , a given offset was outside the bounds of the dataview or offset + length was larger than a length of given buffer .

ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT #

While calling napi_create_typedarray() , the provided offset was not a multiple of the element size.

ERR_NAPI_INVALID_TYPEDARRAY_LENGTH #

While calling napi_create_typedarray() , (length * size_of_element) + byte_offset was larger than the length of given buffer .

ERR_NAPI_TSFN_CALL_JS #

An error occurred while invoking the JavaScript portion of the thread-safe function.

ERR_NAPI_TSFN_GET_UNDEFINED #

An error occurred while attempting to retrieve the JavaScript undefined value.

ERR_NAPI_TSFN_START_IDLE_LOOP #

On the main thread, values are removed from the queue associated with the thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop.

ERR_NAPI_TSFN_STOP_IDLE_LOOP #

Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop.

ERR_NOT_BUILDING_SNAPSHOT #

An attempt was made to use operations that can only be used when building V8 startup snapshot even though Node.js isn’t building one.

ERR_NO_CRYPTO #

An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support.

ERR_NO_ICU #

An attempt was made to use features that require ICU, but Node.js was not compiled with ICU support.

ERR_NON_CONTEXT_AWARE_DISABLED #

A non-context-aware native addon was loaded in a process that disallows them.

ERR_OUT_OF_RANGE #

A given value is out of the accepted range.

ERR_PACKAGE_IMPORT_NOT_DEFINED #

The package.json «imports» field does not define the given internal package specifier mapping.

ERR_PACKAGE_PATH_NOT_EXPORTED #

The package.json «exports» field does not export the requested subpath. Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL.

ERR_PARSE_ARGS_INVALID_OPTION_VALUE #

When strict set to true , thrown by util.parseArgs() if a value is provided for an option of type , or if a value is provided for an option of type .

ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL #

Thrown by util.parseArgs() , when a positional argument is provided and allowPositionals is set to false .

ERR_PARSE_ARGS_UNKNOWN_OPTION #

When strict set to true , thrown by util.parseArgs() if an argument is not configured in options .

ERR_PERFORMANCE_INVALID_TIMESTAMP #

An invalid timestamp value was provided for a performance mark or measure.

ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS #

Invalid options were provided for a performance measure.

ERR_PROTO_ACCESS #

Accessing Object.prototype.__proto__ has been forbidden using —disable-proto=throw . Object.getPrototypeOf and Object.setPrototypeOf should be used to get and set the prototype of an object.

ERR_REQUIRE_ESM #

An attempt was made to require() an ES Module.

ERR_SCRIPT_EXECUTION_INTERRUPTED #

Script execution was interrupted by SIGINT (For example, Ctrl + C was pressed.)

ERR_SCRIPT_EXECUTION_TIMEOUT #

Script execution timed out, possibly due to bugs in the script being executed.

ERR_SERVER_ALREADY_LISTEN #

The server.listen() method was called while a net.Server was already listening. This applies to all instances of net.Server , including HTTP, HTTPS, and HTTP/2 Server instances.

ERR_SERVER_NOT_RUNNING #

The server.close() method was called when a net.Server was not running. This applies to all instances of net.Server , including HTTP, HTTPS, and HTTP/2 Server instances.

ERR_SOCKET_ALREADY_BOUND #

An attempt was made to bind a socket that has already been bound.

ERR_SOCKET_BAD_BUFFER_SIZE #

An invalid (negative) size was passed for either the recvBufferSize or sendBufferSize options in dgram.createSocket() .

ERR_SOCKET_BAD_PORT #

An API function expecting a port >= 0 and ERR_SOCKET_BAD_TYPE #

An API function expecting a socket type ( udp4 or udp6 ) received an invalid value.

ERR_SOCKET_BUFFER_SIZE #

While using dgram.createSocket() , the size of the receive or send Buffer could not be determined.

ERR_SOCKET_CLOSED #

An attempt was made to operate on an already closed socket.

ERR_SOCKET_CLOSED_BEFORE_CONNECTION #

When calling net.Socket.write() on a connecting socket and the socket was closed before the connection was established.

ERR_SOCKET_DGRAM_IS_CONNECTED #

A dgram.connect() call was made on an already connected socket.

ERR_SOCKET_DGRAM_NOT_CONNECTED #

A dgram.disconnect() or dgram.remoteAddress() call was made on a disconnected socket.

ERR_SOCKET_DGRAM_NOT_RUNNING #

A call was made and the UDP subsystem was not running.

ERR_SRI_PARSE #

A string was provided for a Subresource Integrity check, but was unable to be parsed. Check the format of integrity attributes by looking at the Subresource Integrity specification.

ERR_STREAM_ALREADY_FINISHED #

A stream method was called that cannot complete because the stream was finished.

ERR_STREAM_CANNOT_PIPE #

An attempt was made to call stream.pipe() on a Writable stream.

ERR_STREAM_DESTROYED #

A stream method was called that cannot complete because the stream was destroyed using stream.destroy() .

ERR_STREAM_NULL_VALUES #

An attempt was made to call stream.write() with a null chunk.

ERR_STREAM_PREMATURE_CLOSE #

An error returned by stream.finished() and stream.pipeline() , when a stream or a pipeline ends non gracefully with no explicit error.

ERR_STREAM_PUSH_AFTER_EOF #

An attempt was made to call stream.push() after a null (EOF) had been pushed to the stream.

ERR_STREAM_UNSHIFT_AFTER_END_EVENT #

An attempt was made to call stream.unshift() after the ‘end’ event was emitted.

ERR_STREAM_WRAP #

Prevents an abort if a string decoder was set on the Socket or if the decoder is in objectMode .

ERR_STREAM_WRITE_AFTER_END #

An attempt was made to call stream.write() after stream.end() has been called.

ERR_STRING_TOO_LONG #

An attempt has been made to create a string longer than the maximum allowed length.

ERR_SYNTHETIC #

An artificial error object used to capture the call stack for diagnostic reports.

ERR_SYSTEM_ERROR #

An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an err.info object property with additional details.

ERR_TAP_LEXER_ERROR #

An error representing a failing lexer state.

ERR_TAP_PARSER_ERROR #

An error representing a failing parser state. Additional information about the token causing the error is available via the cause property.

ERR_TAP_VALIDATION_ERROR #

This error represents a failed TAP validation.

ERR_TEST_FAILURE #

This error represents a failed test. Additional information about the failure is available via the cause property. The failureType property specifies what the test was doing when the failure occurred.

ERR_TLS_CERT_ALTNAME_FORMAT #

This error is thrown by checkServerIdentity if a user-supplied subjectaltname property violates encoding rules. Certificate objects produced by Node.js itself always comply with encoding rules and will never cause this error.

ERR_TLS_CERT_ALTNAME_INVALID #

While using TLS, the host name/IP of the peer did not match any of the subjectAltNames in its certificate.

ERR_TLS_DH_PARAM_SIZE #

While using TLS, the parameter offered for the Diffie-Hellman ( DH ) key-agreement protocol is too small. By default, the key length must be greater than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security.

ERR_TLS_HANDSHAKE_TIMEOUT #

A TLS/SSL handshake timed out. In this case, the server must also abort the connection.

ERR_TLS_INVALID_CONTEXT #

The context must be a SecureContext .

ERR_TLS_INVALID_PROTOCOL_METHOD #

The specified secureProtocol method is invalid. It is either unknown, or disabled because it is insecure.

ERR_TLS_INVALID_PROTOCOL_VERSION #

Valid TLS protocol versions are ‘TLSv1’ , ‘TLSv1.1’ , or ‘TLSv1.2’ .

ERR_TLS_INVALID_STATE #

The TLS socket must be connected and securely established. Ensure the ‘secure’ event is emitted before continuing.

ERR_TLS_PROTOCOL_VERSION_CONFLICT #

Attempting to set a TLS protocol minVersion or maxVersion conflicts with an attempt to set the secureProtocol explicitly. Use one mechanism or the other.

ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED #

Failed to set PSK identity hint. Hint may be too long.

ERR_TLS_RENEGOTIATION_DISABLED #

An attempt was made to renegotiate TLS on a socket instance with TLS disabled.

ERR_TLS_REQUIRED_SERVER_NAME #

While using TLS, the server.addContext() method was called without providing a host name in the first parameter.

ERR_TLS_SESSION_ATTACK #

An excessive amount of TLS renegotiations is detected, which is a potential vector for denial-of-service attacks.

ERR_TLS_SNI_FROM_SERVER #

An attempt was made to issue Server Name Indication from a TLS server-side socket, which is only valid from a client.

ERR_TRACE_EVENTS_CATEGORY_REQUIRED #

The trace_events.createTracing() method requires at least one trace event category.

ERR_TRACE_EVENTS_UNAVAILABLE #

The node:trace_events module could not be loaded because Node.js was compiled with the —without-v8-platform flag.

ERR_TRANSFORM_ALREADY_TRANSFORMING #

A Transform stream finished while it was still transforming.

ERR_TRANSFORM_WITH_LENGTH_0 #

A Transform stream finished with data still in the write buffer.

ERR_TTY_INIT_FAILED #

The initialization of a TTY failed due to a system error.

ERR_UNAVAILABLE_DURING_EXIT #

Function was called within a process.on(‘exit’) handler that shouldn’t be called within process.on(‘exit’) handler.

ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET #

process.setUncaughtExceptionCaptureCallback() was called twice, without first resetting the callback to null .

This error is designed to prevent accidentally overwriting a callback registered from another module.

ERR_UNESCAPED_CHARACTERS #

A string that contained unescaped characters was received.

ERR_UNHANDLED_ERROR #

An unhandled error occurred (for instance, when an ‘error’ event is emitted by an EventEmitter but an ‘error’ handler is not registered).

ERR_UNKNOWN_BUILTIN_MODULE #

Used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an internal bug within the Node.js binary itself.

ERR_UNKNOWN_CREDENTIAL #

A Unix group or user identifier that does not exist was passed.

ERR_UNKNOWN_ENCODING #

An invalid or unknown encoding option was passed to an API.

ERR_UNKNOWN_FILE_EXTENSION #

An attempt was made to load a module with an unknown or unsupported file extension.

ERR_UNKNOWN_MODULE_FORMAT #

An attempt was made to load a module with an unknown or unsupported format.

ERR_UNKNOWN_SIGNAL #

An invalid or unknown process signal was passed to an API expecting a valid signal (such as subprocess.kill() ).

ERR_UNSUPPORTED_DIR_IMPORT #

import a directory URL is unsupported. Instead, self-reference a package using its name and define a custom subpath in the «exports» field of the package.json file.

ERR_UNSUPPORTED_ESM_URL_SCHEME #

import with URL schemes other than file and data is unsupported.

ERR_USE_AFTER_CLOSE #

An attempt was made to use something that was already closed.

ERR_VALID_PERFORMANCE_ENTRY_TYPE #

While using the Performance Timing API ( perf_hooks ), no valid performance entry types are found.

ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING #

A dynamic import callback was not specified.

ERR_VM_MODULE_ALREADY_LINKED #

The module attempted to be linked is not eligible for linking, because of one of the following reasons:

  • It has already been linked ( linkingStatus is ‘linked’ )
  • It is being linked ( linkingStatus is ‘linking’ )
  • Linking has failed for this module ( linkingStatus is ‘errored’ )

ERR_VM_MODULE_CACHED_DATA_REJECTED #

The cachedData option passed to a module constructor is invalid.

ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA #

Cached data cannot be created for modules which have already been evaluated.

ERR_VM_MODULE_DIFFERENT_CONTEXT #

The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context.

ERR_VM_MODULE_LINK_FAILURE #

The module was unable to be linked due to a failure.

ERR_VM_MODULE_NOT_MODULE #

The fulfilled value of a linking promise is not a vm.Module object.

ERR_VM_MODULE_STATUS #

The current module’s status does not allow for this operation. The specific meaning of the error depends on the specific function.

ERR_WASI_ALREADY_STARTED #

The WASI instance has already started.

ERR_WASI_NOT_STARTED #

The WASI instance has not been started.

ERR_WEBASSEMBLY_RESPONSE #

The Response that has been passed to WebAssembly.compileStreaming or to WebAssembly.instantiateStreaming is not a valid WebAssembly response.

ERR_WORKER_INIT_FAILED #

The Worker initialization failed.

ERR_WORKER_INVALID_EXEC_ARGV #

The execArgv option passed to the Worker constructor contains invalid flags.

ERR_WORKER_NOT_RUNNING #

An operation failed because the Worker instance is not currently running.

ERR_WORKER_OUT_OF_MEMORY #

The Worker instance terminated because it reached its memory limit.

ERR_WORKER_PATH #

The path for the main script of a worker is neither an absolute path nor a relative path starting with ./ or ../ .

ERR_WORKER_UNSERIALIZABLE_ERROR #

All attempts at serializing an uncaught exception from a worker thread failed.

ERR_WORKER_UNSUPPORTED_OPERATION #

The requested functionality is not supported in worker threads.

ERR_ZLIB_INITIALIZATION_FAILED #

Creation of a zlib object failed due to incorrect configuration.

HPE_HEADER_OVERFLOW #

History

Max header size in http_parser was set to 8 KiB.

Too much HTTP header data was received. In order to protect against malicious or malconfigured clients, if more than 8 KiB of HTTP header data is received then HTTP parsing will abort without a request or response object being created, and an Error with this code will be emitted.

HPE_UNEXPECTED_CONTENT_LENGTH #

Server is sending both a Content-Length header and Transfer-Encoding: chunked .

Transfer-Encoding: chunked allows the server to maintain an HTTP persistent connection for dynamically generated content. In this case, the Content-Length HTTP header cannot be used.

Use Content-Length or Transfer-Encoding: chunked .

MODULE_NOT_FOUND #

History

Version Changes
v11.4.0, v10.15.0

Added requireStack property.

A module file could not be resolved by the CommonJS modules loader while attempting a require() operation or when loading the program entry point.

Legacy Node.js error codes #

ERR_CANNOT_TRANSFER_OBJECT #

The value passed to postMessage() contained an object that is not supported for transferring.

ERR_CRYPTO_HASH_DIGEST_NO_UTF16 #

The UTF-16 encoding was used with hash.digest() . While the hash.digest() method does allow an encoding argument to be passed in, causing the method to return a string rather than a Buffer , the UTF-16 encoding (e.g. ucs or utf16le ) is not supported.

ERR_HTTP2_FRAME_ERROR #

Used when a failure occurs sending an individual frame on the HTTP/2 session.

ERR_HTTP2_HEADERS_OBJECT #

Used when an HTTP/2 Headers Object is expected.

ERR_HTTP2_HEADER_REQUIRED #

Used when a required header is missing in an HTTP/2 message.

ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND #

HTTP/2 informational headers must only be sent prior to calling the Http2Stream.prototype.respond() method.

ERR_HTTP2_STREAM_CLOSED #

Used when an action has been performed on an HTTP/2 Stream that has already been closed.

ERR_HTTP_INVALID_CHAR #

Used when an invalid character is found in an HTTP response status message (reason phrase).

ERR_INDEX_OUT_OF_RANGE #

A given index was out of the accepted range (e.g. negative offsets).

ERR_INVALID_OPT_VALUE #

An invalid or unexpected value was passed in an options object.

ERR_INVALID_OPT_VALUE_ENCODING #

An invalid or unknown file encoding was passed.

ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST #

This error code was replaced by ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST in Node.js v15.0.0, because it is no longer accurate as other types of transferable objects also exist now.

ERR_NAPI_CONS_PROTOTYPE_OBJECT #

Used by the Node-API when Constructor.prototype is not an object.

ERR_NETWORK_IMPORT_BAD_RESPONSE #

Response was received but was invalid when importing a module over the network.

ERR_NETWORK_IMPORT_DISALLOWED #

A network module attempted to load another module that it is not allowed to load. Likely this restriction is for security reasons.

ERR_NO_LONGER_SUPPORTED #

A Node.js API was called in an unsupported manner, such as Buffer.write(string, encoding, offset[, length]) .

ERR_OPERATION_FAILED #

An operation failed. This is typically used to signal the general failure of an asynchronous operation.

ERR_OUTOFMEMORY #

Used generically to identify that an operation caused an out of memory condition.

ERR_PARSE_HISTORY_DATA #

The node:repl module was unable to parse data from the REPL history file.

ERR_SOCKET_CANNOT_SEND #

Data could not be sent on a socket.

ERR_STDERR_CLOSE #

History

Version Changes
v12.0.0

Rather than emitting an error, process.stderr.end() now only closes the stream side but not the underlying resource, making this error obsolete.

Removed in: v10.12.0

An attempt was made to close the process.stderr stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code.

ERR_STDOUT_CLOSE #

History

Version Changes
v10.12.0

Rather than emitting an error, process.stderr.end() now only closes the stream side but not the underlying resource, making this error obsolete.

Removed in: v10.12.0

An attempt was made to close the process.stdout stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code.

ERR_STREAM_READ_NOT_IMPLEMENTED #

Used when an attempt is made to use a readable stream that has not implemented readable._read() .

ERR_TLS_RENEGOTIATION_FAILED #

Used when a TLS renegotiation request has failed in a non-specific way.

ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER #

A SharedArrayBuffer whose memory is not managed by the JavaScript engine or by Node.js was encountered during serialization. Such a SharedArrayBuffer cannot be serialized.

This can only happen when native addons create SharedArrayBuffer s in «externalized» mode, or put existing SharedArrayBuffer into externalized mode.

ERR_UNKNOWN_STDIN_TYPE #

An attempt was made to launch a Node.js process with an unknown stdin file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.

ERR_UNKNOWN_STREAM_TYPE #

An attempt was made to launch a Node.js process with an unknown stdout or stderr file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.

ERR_V8BREAKITERATOR #

The V8 BreakIterator API was used but the full ICU data set is not installed.

ERR_VALUE_OUT_OF_RANGE #

Used when a given value is out of the accepted range.

ERR_VM_MODULE_NOT_LINKED #

The module must be successfully linked before instantiation.

ERR_VM_MODULE_LINKING_ERRORED #

The linker function returned a module for which linking has failed.

ERR_WORKER_UNSUPPORTED_EXTENSION #

The pathname used for the main script of a worker has an unknown file extension.

ERR_ZLIB_BINDING_CLOSED #

Used when an attempt is made to use a zlib object after it has already been closed.

Источник

Adblock
detector

Version Changes
v10.12.0

Понравилась статья? Поделить с друзьями:
  • Custom 400 error
  • Curtis 1232 ошибки
  • Curtis 1230 ошибки
  • Cursor error css
  • Curses error setupterm could not find terminal