Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuro

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
012345678901234567890123456789012345678901234567890123456789
Ieri
012345678901234567890123456789012345678901234567890123456789
Visualizzazioni totali
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di JavaScript
JavaScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: Async and Closures
Discussioni

Guida a JavaScript · 5/6

Errors and Testing

Per ora questo capitolo è disponibile solo in inglese.

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
}
Domande su questo capitolo?
Capitolo precedenteModules and PackagesCapitolo successivoKey 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 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.