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.

Frequently asked questions

How does JavaScript handle custom error?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Custom Error Classes" snippet in JavaScript uses `class CustomError extends Error {`.
Which code does the JavaScript example use?
The "Custom Error Classes" snippet uses `class CustomError extends Error {`, from the Error Handling section of the JavaScript cheat sheet.
Which stacks cover "custom error" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Custom Error Classes": Custom errors let you add context (which field, which resource) and enable precise catch handling with instanceof checks.