Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Normalize thrown values into errors in JavaScript

51 Anything can be thrown, so normalise it

fair

throw accepts any value. Catch a string, a number, undefined and an object that merely looks like an error, and show what your handler gets. Then write normalise(value) that turns each of them into a real Error without losing the original.

Stuck? Three hints, smallest first
  1. 1. The catch block runs for every one of them, including throw undefined.
  2. 2. Reading .message off a non-object is undefined; reading it off undefined throws inside your handler.
  3. 3. An object with a message property is not an Error. Keep it as evidence rather than trusting it.

The answer

const caught = (fn) => { try { fn(); return 'nothing was thrown'; } catch (err) { return err; } };

const aString = caught(() => { throw 'till offline'; });
const aNumber = caught(() => { throw 404; });
const nothing = caught(() => { throw undefined; });
const lookalike = caught(() => { throw { code: 'E_TILL', message: 'looks like an error' }; });

const handlerThrew = (() => {
  try {
    try { throw undefined; }
    catch (err) { return 'message was ' + err.message; }     // the handler is now the bug
  } catch (err) { return err.name; }
})();

function normalise(value) {
  if (value instanceof Error) return value;
  if (typeof value === 'string') return new Error(value);
  if (value !== null && typeof value === 'object' && typeof value.message === 'string') {
    return Object.assign(new Error(value.message), { thrown: value });
  }
  return new Error('non-error thrown: ' + String(value));
}

const real = new RangeError('a genuine error');
const normalised = [aString, aNumber, nothing, lookalike, real].map(normalise);
const messages = normalised.map((err) => err.message);
const allErrors = normalised.every((err) => err instanceof Error);
const untouched = normalise(real) === real;
const evidenceKept = normalised[3].thrown.code;
const fromRejection = await Promise.reject('a rejected string').catch((value) => [typeof value, normalise(value).message]);

console.log('a thrown string  :', typeof aString, JSON.stringify(aString), '- message:', aString.message);
console.log('throw undefined  :', nothing === undefined, '- and the handler:', handlerThrew);
console.log('normalised       :', messages);
console.log('evidence kept    :', normalised[3].thrown);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a thrown string arrives as a string, with no message of its own', [typeof aString, aString.message === undefined], ['string', true]);
test('a number too, and neither has a stack', [aNumber, normalised[1] instanceof Error], [404, true]);
test('catch runs even for throw undefined', nothing === undefined, true);
test('and reading .message off it makes the handler itself throw', handlerThrew, 'TypeError');
test('an object with a message property is still not an Error', [lookalike instanceof Error, lookalike.message], [false, 'looks like an error']);
test('normalise gives every one of them a real Error with a usable message', [allErrors, messages], [true, ['till offline', 'non-error thrown: 404', 'non-error thrown: undefined', 'looks like an error', 'a genuine error']]);
test('a real error passes through as the same object, keeping its stack', untouched, true);
test('and a lookalike keeps the original as evidence', evidenceKept, 'E_TILL');
test('a rejection with a non-Error needs exactly the same treatment', fromRejection, ['string', 'a rejected string']);

throw is untyped, so catch is untyped. Every handler you write is handed a value of unknown shape, and the habit of reaching straight for err.message is what turns somebody else's careless throw ‘failed’ into a TypeError inside your error handling — the fourth assertion, and the reason a crash report sometimes points at the catch block rather than the failure.

The lookalike is the interesting case. Objects with a message field come out of older libraries, out of JSON error responses, and out of anything that crossed a serialisation boundary as in exercise 42. Treating it as an Error because it quacks like one loses the class and the stack; wrapping it and keeping the original under thrown gives you both a real error to propagate and the raw payload to log.

Two rules follow. In your own code, always throw new Error(...) — a subclass from exercise 34 where it helps dispatch — because a string reason has no stack, no name and nowhere to hang a cause. And at every boundary you do not control, normalise on the way in. TypeScript makes this unavoidable rather than optional: catch (err) is typed unknown under modern settings, precisely because the language cannot promise you anything better.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.