Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

JavaScript docs
JavaScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: Async and Closures
Discussions

JavaScript guide · 5/6

Errors and Testing

Sooner or later every program meets bad input, a dropped connection or a missing file. This chapter covers throwing and catching errors, the built-in error types, custom errors, error handling in async code, and testing with the runner built into Node.js.

throw, try, catch and finally

Signal a problem with throw and handle it with try...catch. A finally block runs whether or not anything failed, which makes it the right place for cleanup. Always throw Error objects rather than strings: they carry a stack that tells you where things went wrong.

function parseAge(input) {
  const age = Number(input);
  if (!Number.isInteger(age) || age < 0) {
    throw new RangeError(`Not a valid age: ${input}`);
  }
  return age;
}

try {
  console.log(parseAge("29")); // 29
  console.log(parseAge("-3")); // throws here
  console.log("never reached");
} catch (error) {
  console.error(error.name, error.message); // RangeError Not a valid age: -3
} finally {
  console.log("done checking");
}

Built-in error types

The engine and built-in functions throw different subclasses of Error, which you can tell apart with instanceof.

TypeTypical cause
TypeErrorReading a property of undefined, calling a non-function
ReferenceErrorUsing a variable that was never declared
RangeErrorA value outside the allowed range, e.g. new Array(-1)
SyntaxErrorInvalid code, or bad input to JSON.parse

Custom errors and cause

Application-specific failures are easier to handle as subclasses of Error. When you catch one error and throw another, pass the original as cause so the root problem is not lost.

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

function loadConfig(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error("Could not read config", { cause: error });
  }
}

try {
  throw new NotFoundError("user 42");
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log("respond with 404:", error.message);
  } else {
    throw error; // not ours to handle
  }
}

try {
  loadConfig("{ broken");
} catch (error) {
  console.log(error.message, "caused by", error.cause.name); // ... SyntaxError
}

Catching everything and carrying on silently hides bugs. Catch what you can actually handle and rethrow the rest.

Errors in async code

try...catch only sees a rejected Promise if you await it; without await, the rejection slips past. Node.js terminates the process on an unhandled rejection by default, so always handle them.

import { readFile } from "node:fs/promises";

async function readJson(path) {
  try {
    return JSON.parse(await readFile(path, "utf8"));
  } catch (error) {
    if (error.code === "ENOENT") return null; // missing file is fine
    throw error;
  }
}

// with a then chain, attach .catch
readJson("settings.json")
  .then((data) => console.log(data ?? "no settings"))
  .catch((error) => console.error("read failed:", error));

// see every outcome, success or failure
const results = await Promise.allSettled([readJson("a.json"), readJson("b.json")]);
for (const r of results) {
  console.log(r.status, r.status === "fulfilled" ? r.value : r.reason.message);
}

An error thrown inside a setTimeout callback also escapes a surrounding try...catch, because the callback runs later on its own. Chapter 6 explains why.

Testing with node:test

Node.js ships a test runner, node:test, and an assertion module, node:assert. Name files like *.test.js and node --test finds and runs them.

// age.test.js
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { parseAge } from "./age.js";

describe("parseAge", () => {
  it("converts numeric strings", () => {
    assert.equal(parseAge("29"), 29);
  });

  it("rejects negative numbers", () => {
    assert.throws(() => parseAge("-1"), RangeError);
  });

  it("handles async failures", async () => {
    await assert.rejects(Promise.reject(new Error("boom")), /boom/);
  });

  it("compares objects deeply", () => {
    assert.deepEqual({ a: [1, 2] }, { a: [1, 2] });
  });
});
node --test
node --test --watch

Other test runners

For richer features, the community favorites are Vitest, which is fast and pairs naturally with Vite, and Jest, which has years of documentation behind it. Both use a similar describe / it / expect style.

// sum.test.js (Vitest)
import { describe, it, expect } from "vitest";
import sum from "./math.js";

describe("sum", () => {
  it("adds every argument", () => {
    expect(sum(1, 2, 3)).toBe(6);
  });

  it("returns 0 with no arguments", () => {
    expect(sum()).toBe(0);
  });
});

Summary

  • Throw Error objects and catch them only where you can handle them.
  • Do cleanup in finally; preserve root causes with cause.
  • Handle async failures with await plus try...catch, or with .catch().
  • node:test and node:assert/strict cover a lot; reach for Vitest or Jest when you need more.
Questions about this chapter?
Previous chapterModules and PackagesNext chapterKey Concepts: Async and Closures

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.