Labs ICT
🎓 SIWES/IT Login

Custom Errors

1 min read | JavaScript Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

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);
  }
}