Error Handling
try / catch / finally
try {
const data = JSON.parse(text); // may throw
} catch (err) {
console.error("Bad JSON:", err.message);
} finally {
hideSpinner(); // always runs
}
Throwing your own errors
throw new Error("Email is required");. Always throw Error objects (not plain strings) so you get a message and a stack trace.
Error types you'll see
| Error | Usually means |
|---|---|
TypeError | using something the wrong way: undefined.name, calling a non-function |
ReferenceError | a variable doesn't exist (typo) |
SyntaxError | invalid code, or invalid JSON in JSON.parse |
RangeError | a value out of range |
Async errors
- With
async/await, usetry/catch. - With
.then(), end the chain with.catch(). - An unhandled rejection shows in the console; always handle promises.
Errors users should see
- Show a friendly message and a way to retry; never a raw stack trace.
- Log details for yourself (console, or Sentry in production).
- Validate input before it causes an error.
💡 Read errors from the top line: it names the problem and the file:line where it happened.
Example
function parseAge(text) {
const age = Number(text);
if (Number.isNaN(age)) throw new Error(`"${text}" is not a number`);
if (age < 0) throw new RangeError("Age can't be negative");
return age;
}
for (const input of ["21", "abc", "-4"]) {
try {
console.log("Age:", parseAge(input));
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}
// Age: 21
// Error: "abc" is not a number
// RangeError: Age can't be negative
async function safeFetch(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.warn("Request failed:", err.message);
return null; // let the UI show "Try again"
}
}