Labs ICT
Pro Login

Custom Errors

1 min read | JavaScript Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Custom Error Classes

Create custom error classes by extending the built-in Error. This helps distinguish different error types in your app.

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

try {
  throw new ValidationError("Invalid email format");
} catch (err) {
  console.log(err.name);
  console.log(err.message);
}

Extending Error with Properties

Add extra properties to your custom error to carry additional context like status codes or field names.

class HttpError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.name = "HttpError";
    this.statusCode = statusCode;
  }
}

async function fetchUser(id) {
  const res = await fetch("/api/users/" + id);
  if (!res.ok) {
    throw new HttpError("User not found", res.status);
  }
  return res.json();
}

fetchUser(999).catch(err => {
  console.log(err.name, err.statusCode, err.message);
});

Multiple Custom Error Types

Define several custom error classes to handle different failure modes precisely.

class NotFoundError extends Error {
  constructor(resource) {
    super(resource + " not found");
    this.name = "NotFoundError";
  }
}

class AuthError extends Error {
  constructor() {
    super("Authentication failed");
    this.name = "AuthError";
  }
}

try {
  throw new NotFoundError("Product");
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log("Handle 404:", err.message);
  } else if (err instanceof AuthError) {
    console.log("Handle 401:", err.message);
  }
}