Last active
July 13, 2020 16:30
-
-
Save okovalov/8a85c75f7c963ca7806220e90fe7b517 to your computer and use it in GitHub Desktop.
How to create a custom JS Error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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