On this page
  1. ES Modules & Error Handling
  2. Contents
  3. Static & Dynamic ES Modules
  4. Custom Errors & Error.cause

ES Modules & Error Handling

Prev: Event Loop & Async Programming | Up: tutorials | Next: Iterators, Generators & Iterator Helpers
Rel: Interactive & Scripting, Promise & Async
Ref: MDN Web Docs — JavaScript Modules
Tags: #public #web #javascript #tutorials #modules #errors


Contents


Static & Dynamic ES Modules

ES Modules run in strict mode, have their own module scope, execute once per specifier, and support top-level await:

// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }

// app.js
import { area } from "./math.js";

// Lazy dynamic import (returns a Promise)
const mod = await import("./math.js");

Custom Errors & Error.cause

Wrap low-level errors with { cause } so root-cause diagnostics are preserved:

class ApiError extends Error {
  constructor(message, { status, cause } = {}) {
    super(message, { cause });
    this.name = "ApiError";
    this.status = status;
  }
}

try {
  JSON.parse("{bad");
} catch (err) {
  throw new ApiError("Failed to decode payload", { status: 400, cause: err });
}

Linked from

Related notes