InterviewHubPRO
Section Overview
Q509

Question 509 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

98%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

How do you implement a custom error class in JavaScript?

Custom error classes allow you to create specific error types with additional properties and methods, making error handling more precise.

Basic custom error:

javascript
 class CustomError extends Error {
   constructor(message) {
     super(message);
     this.name = 'CustomError';
   }
 }

 throw new CustomError('Something went wrong');

Error with additional properties:

javascript
 class ValidationError extends Error {
   constructor(message, field) {
     super(message);
     this.name = 'ValidationError';
     this.field = field;
     this.timestamp = new Date();
   }
 }

 try {
   throw new ValidationError('Invalid email', 'email');
 } catch (error) {
   if (error instanceof ValidationError) {
     console.log(`${error.field}: ${error.message}`);
     // email: Invalid email
   }
 }

HTTP error class:

javascript
 class HTTPError extends Error {
   constructor(message, status, response) {
     super(message);
     this.name = 'HTTPError';
     this.status = status;
     this.response = response;
   }

   get isClientError() {
     return this.status >= 400 && this.status < 500;
   }

   get isServerError() {
     return this.status >= 500;
   }
 }

 async function fetchData(url) {
   const response = await fetch(url);
   if (!response.ok) {
     throw new HTTPError(
       'Failed to fetch',
       response.status,
       await response.json()
     );
   }
   return response.json();
 }

 try {
   await fetchData('/api/users');
 } catch (error) {
   if (error instanceof HTTPError && error.isClientError) {
     console.log('Client error:', error.message);
   }
 }

Error factory pattern:

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

   static badRequest(message, metadata) {
     return new AppError(message, 'BAD_REQUEST', metadata);
   }

   static notFound(resource) {
     return new AppError(
       `${resource} not found`,
       'NOT_FOUND',
       { resource }
     );
   }

   static unauthorized(message) {
     return new AppError(message, 'UNAUTHORIZED');
   }
 }

 throw AppError.notFound('User');
 throw AppError.badRequest('Invalid input', { field: 'email' });

Error with stack trace customization:

javascript
 class DatabaseError extends Error {
   constructor(message, query) {
     super(message);
     this.name = 'DatabaseError';
     this.query = query;

     // Maintain proper stack trace
     if (Error.captureStackTrace) {
       Error.captureStackTrace(this, DatabaseError);
     }
   }
 }