Zum Hauptinhalt springen
ProdukteDesktop-WerkzeugeTASTECADZeichnungsprüfungTASTEFILESDateiverwaltungTASTEFTPDateiübertragungTASTESSHRemote-ArbeitsbereichTASTEZIPKomprimieren und EntpackenEntwicklerwerkzeugeTASTECODEIntegrierte Entwicklungsumgebung für RustTASTESTUDIOIntegrierte Entwicklungs- und TestumgebungTASTEETLDatenintegration (ETL)ServerTASTEREMOTERemote-Desktop-ServerTASTEGEOGeodatenserverTASTEMAILE-Mail-ArbeitsbereichErste SchritteDownloadsDokumentationKaufenAlle Produkte
Marktplatz
Neuigkeiten
TechnikNeuigkeitenEntwickler-News von heuteEntwicklerdokuProgrammiersprachenRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp- & Desktop-FrameworksTauriFlutterReact NativeElectronAlgorithmenAlgorithmus-GrundlagenKernalgorithmenFortgeschrittene AlgorithmenAlgorithmen für die Praxis
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcaseCommunity-Leitfaden
ZusammenarbeitWissenstransferWebsite-AufbauDesktop-App-AufbauRelease- und ZahlungspipelineVertriebspartnerKontakt
DiensteRemote-DesktopIndividuelle Installationspakete
TASTEDEV
Produkte

Desktop-Werkzeuge

TASTECADKomplexe Zeichnungen, mühelos geöffnetTASTEFILESNur die Dateien, die zählen – in BestzeitTASTEFTPDer aufgeräumteste Weg für Ihre DateienTASTESSHDie stärkere Verbindung zu Ihren ServernTASTEZIPSchneller packen, sicherer entpacken

Entwicklerwerkzeuge

TASTECODERust-Apps bearbeiten, bauen, debuggen und testen – alles in einem FensterTASTESTUDIOVom Bearbeiten bis zu Remote-Tests und freigegebenen KI-KorrekturenTASTEETLDaten bewegen, die Werte im Blick

Server

TASTEREMOTEEin Remote-Desktop auf Ihrem eigenen ServerTASTEGEOEin GeoServer-kompatibler Geodatenserver, neu aufgebaut in RustTASTEMAILIhre E-Mail wieder in Ihrer Hand

Erste Schritte

DownloadsNeueste Versionen aller ProdukteDokuSo nutzen Sie jedes ProduktKaufenAbos und DauerlizenzenAlle ProdukteAlle Produkte im Überblick
Alle Produkte
MarktplatzNeuigkeiten
Technik

Neuigkeiten

Entwickler-News von heuteOffizielle Meldungen zu Sprachen, Frameworks, GitHub und KIEntwicklerdokuAnleitungen zu Sprachen, Frameworks und Algorithmen

Programmiersprachen

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App- & Desktop-FrameworksTauriFlutterReact NativeElectron

Algorithmen

Algorithmus-GrundlagenKomplexitätsanalyse · Sortieren · Suchen · Grundlegende Datenstrukturen · Bäume und HeapsKernalgorithmenGraphtraversierung · Kürzeste Wege und minimale Spannbäume · Dynamische Programmierung · Greedy-Algorithmen · Teile und herrsche · BacktrackingFortgeschrittene AlgorithmenZeichenkettenalgorithmen · Mathematik und Zahlentheorie · Bitmanipulation · Segmentbäume · Union-FindAlgorithmen für die PraxisStrategie für Coding-Interviews · LRU-Cache · Rate Limiting · Konsistentes Hashing
Alle Entwicklungsdokumente
Community
ProjekteEntwickler und Projekte entdeckenEntwicklungslogsEntscheidungen und ErkenntnissePromptsWiederverwendbare AnweisungenProbleme mit KI-ToolsProbleme und Workarounds für Claude, Codex, GeminiShowcaseFertige ErgebnisseCommunity-LeitfadenWie wir offen entwickeln
Zusammenarbeit
WissenstransferNative Apps mit Rust und eguiWebsite-Aufbau10 Sprachen, Konten, Dokumentation und DownloadsDesktop-App-AufbauRust und egui, ohne WebViewRelease- und ZahlungspipelineSignatur, MSI, deb, rpm, AppImage, PrüfsummenVertriebspartnerEmpfehlen und 30 % erhaltenKontaktEntwicklung, Partnerschaft, Investition
Dienste
Remote-DesktopIhren Computer im Browser erreichenIndividuelle InstallationspaketeNur nötige Funktionen, Einstellungen vorab
Kaufen
DE
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Anmelden
Anmelden
TASTEDEV

Von kleinen Werkzeugen zu besserer Entwicklung.

support@tastedev.netTASTEDEV unterstützen
ProdukteProduktübersichtKaufenDokuDownloadsMarktplatzSupport
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcase
RichtlinienDatenschutzerklärungNutzungsbedingungenAbo-BedingungenRückerstattungCommunity-Richtlinien
KontoAnmeldenRegistrieren
Besucher
Heute
012345678901234567890123456789012345678901234567890123456789
Gestern
012345678901234567890123456789012345678901234567890123456789
Aufrufe gesamt
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Firma
GXSOFT
Vertretungsberechtigt
CHOI YOUNG GU
Handelsregisternummer
853-44-00368
Anschrift
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefon
+82-10-4404-1523
E-Mail
whitecalvin@tastedev.net
Datenschutzbeauftragter
CHOI YOUNG GU

© 2026 TASTEDEVProduktinformationen basieren auf verifizierten Entwicklungsquellen.Veröffentlicht · wird verbessert

JavaScript-Dokumentation
JavaScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: Async and Closures
Diskussionen

JavaScript-Anleitung · 5/6

Errors and Testing

Dieses Kapitel ist vorerst nur auf Englisch verfügbar.

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
}
Fragen zu diesem Kapitel?
Vorheriges KapitelModules and PackagesNächstes KapitelKey Concepts: Async and Closures

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.

0 Kommentare

Top-KommentareNeueste zuerst

Anmelden · Melde dich an, um einen Kommentar zu schreiben.