Custom error

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Custom Error Classes

JS · Error Handling
syntax
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  }
}
example
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

class NotFoundError extends Error {
  constructor(resource, id) {
    super(`${resource} with id ${id} not found`);
    this.name = "NotFoundError";
    this.resource = resource;
    this.id = id;
  }
}

try {
  throw new ValidationError("email", "Invalid email format");
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(`Field: ${err.field}, Message: ${err.message}`);
  }
}
output
"Field: email, Message: Invalid email format"

Note Custom errors let you add context (which field, which resource) and enable precise catch handling with instanceof checks.

PYPython

Custom Exception Classes

PY · Error Handling
syntax
class MyError(Exception):
    ...
example
class PaymentError(Exception):
    def __init__(self, amount: float, reason: str):
        self.amount = amount
        self.reason = reason
        super().__init__(f"Payment of ${amount:.2f} failed: {reason}")

try:
    raise PaymentError(49.99, "card declined")
except PaymentError as e:
    print(e)
    print(f"Amount: ${e.amount}")
output
Payment of $49.99 failed: card declined
Amount: $49.99

Note Custom exceptions should inherit from Exception (not BaseException). Add meaningful attributes so callers can inspect the error programmatically.