LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 24 of 25

Error Handling Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Error Handling · Study material

Serialising errors for logs and APIs

An error's name, message and stack are not enumerable, so JSON.stringify(error) prints {}. Copy the fields you need into a plain object:

const err = new TypeError("price must be a number", { cause: "bad input" });
console.log(JSON.stringify(err));                       // message, name and stack are not enumerable

function toJSONSafe(e) {
  return { name: e.name, message: e.message, cause: e.cause ?? null };
}
console.log(JSON.stringify(toJSONSafe(err)));

Output

{}
{"name":"TypeError","message":"price must be a number","cause":"bad input"}

The [error, value] pattern

Where failure is normal (parsing user input, optional files), returning the error as a value keeps the happy path flat and forces the caller to look at it:

// Return [error, value] instead of throwing – handy where failure is expected
function attempt(fn, ...args) {
  try {
    return [null, fn(...args)];
  } catch (e) {
    return [e, undefined];
  }
}

const [err1, data] = attempt(JSON.parse, '{"ok":true}');
const [err2] = attempt(JSON.parse, "not json");
console.log(err1, data);
console.log(err2.name);

Output

null { ok: true }
SyntaxError

Which tool for which failure?

SituationApproach
A bug (impossible state)throw and let it crash loudly / log it
Invalid user inputcustom ValidationError or a returned error list
Expected, frequent failurereturn a result ([err, value], null, default)
Low-level error at a higher levelwrap with { cause }
Several independent failuresAggregateError / allSettled
Cleanup (close, unlock, hide spinner)finally
Async failureawait in try/catch, or .catch

Error-handling checklist

  • Throw Error objects with clear messages.
  • Give custom errors a name and useful fields.
  • Catch specific types; re-throw the rest.
  • Never leave a catch block empty – at least log.
  • Put cleanup in finally.
  • Keep the original error as cause when wrapping.
  • Handle every promise: await + try/catch or .catch.
  • Show users friendly messages, log technical details.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links