Skip to content

Instantly share code, notes, and snippets.

@okovalov
Last active July 13, 2020 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okovalov/8a85c75f7c963ca7806220e90fe7b517 to your computer and use it in GitHub Desktop.
Save okovalov/8a85c75f7c963ca7806220e90fe7b517 to your computer and use it in GitHub Desktop.
How to create a custom JS Error
class OutOfFuelError extends Error {
constructor(message) {
super(message)
this.name = "OutOfFuelError"
}
}
class FlatTireError extends Error {}
try {
const car = new Car() //imagine we have a Car object
if (!car.fuel) {
throw new OutOfFuelError('No fuel!')
}
if (car.flatTire) {
throw new FlatTireError('Flat tire!')
}
} catch (err) {
if (err instanceof OutOfFuelError) {
//handle error
} else if (err instanceof FlatTireError) {
//handle error
}
}
// from https://flaviocopes.com/javascript-custom-errors/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment