Code Logo

Custom Error Subclass

Published at25 Jul 2026
JavaScript Functions Hard 0 views
Like0

Write a JavaScript function that defines a custom AppError class extending the built-in Error. The custom error should have a name property, a code property, and a message. It should properly maintain the prototype chain so that instanceof Error and instanceof AppError both work.

Creating custom Error subclasses in JavaScript requires careful handling of the prototype chain. The built-in Error class has special behavior — simply using extends Error may not properly set the name and prototype chain in older environments. Properly implemented custom errors should set this.name to the class name and ensure the prototype is correctly chained.

The Error class and its subclasses are unique in JavaScript because they use a custom prototype chain that includes stack trace capture. When creating custom error hierarchies, you must call super(message) and set this.name = this.constructor.name to ensure proper behavior with error handling tools and logging systems.

Time complexity is O(1) for creating an error instance. The stack trace is captured lazily when the error is created. Space complexity is O(n) where n is the stack trace depth. Custom errors are widely used in Node.js applications for structured error handling.

Edge cases include checking instanceof Error (should be true), instanceof AppError (should be true), the name property matching the class name, and ensuring the error has a stack property that traces back to the creation site.

Example Input & Output

Example 1
Input
"not found",404
Output
true
Explanation

AppError is instance of Error

Example 2
Input
"auth failed",401
Output
true
Explanation

Auth error

Example 3
Input
"timeout",503
Output
true
Explanation

Server error check

Example 4
Input
"bad request",400
Output
true
Explanation

Another error check

Example 5
Input
"ok",200
Output
true
Explanation

Success code error

Algorithm Flow

Recommendation Algorithm Flow for Custom Error Subclass
Recommendation Algorithm Flow for Custom Error Subclass

Solution Approach

class AppError extends Error {
  constructor(message, code) {
    super(message);
    this.name = 'AppError';
    this.code = code;
  }
}

function solution(msg, code) {
  var err = new AppError(msg, code);
  return err instanceof Error && err.name === 'AppError';
}

Best Answers

javascript - Approach 1
class AppError extends Error {
  constructor(message, code) {
    super(message);
    this.name = 'AppError';
    this.code = code;
  }
}

function solution(msg, code) {
  var err = new AppError(msg, code);
  return err instanceof Error && err.name === 'AppError';
}