Throwing and Catching Errors

Errors
πŸ‘¨β€πŸ’Ό We need to convert user input into a number. If the input is invalid, we should throw an error and handle it gracefully so the program can keep running.
Sometimes the best control flow is to stop execution and report a problem:
try {
	const parsedValue = Number('not-a-number')
	if (Number.isNaN(parsedValue)) {
		throw new Error('Something went wrong')
	}
} catch (error) {
	console.error('Caught an error:', error)
}
🐨 Open
index.ts
. The starter provides:
  • rawInput = 'not-a-number'
  • resultMessage starting as ''
  • hadError starting as false
Parse rawInput as a number inside a try/catch. If the input is not a valid number, throw an error whose message is exactly Invalid number: not-a-number (the prefix Invalid number: plus the raw input). On success, set resultMessage to describe the parsed value using the format Parsed value: <number>. On failure, set hadError to true and set resultMessage to Error: <error message> (so the thrown message appears after the Error: prefix).
Export resultMessage and hadError.

Required exports

resultMessage, hadError

Completion criteria (with this fixture)

  • hadError is true
  • resultMessage is exactly Error: Invalid number: not-a-number
Edge cases to keep in mind: valid numeric strings should succeed and set resultMessage to the success format (no error); invalid input must throw and be caught without crashing the program.
In a catch block, the caught value is typed as unknown. Narrow it before you read properties like a message string.
πŸ“œ MDN - throw πŸ“œ MDN - try...catch

Please set the playground first

Loading "Throwing and Catching Errors"
Loading "Throwing and Catching Errors"