Bugs and errors are inevitable in programming. You use a try/catch block when you don't want an error in your script to break your code.
Catch Errors
A try statement lets you test a block of code for errors. And a catch statement lets you handle that error. For example:
try {
//Do something
} catch (e) {
console.error(e);
}
Throw Meaningful Errors
In situations where you don't want to see the ugly JavaScript error, you can throw your own error (an exception) with the use of the throw statement. You can throw errors with an Error object. The string value will be included as the 'message' parameter of the error.
throw new Error('Failed to create supplier');
Errors are objects that can contain multiple parameters. In the example above, the string value is included as the 'message' parameter. You can include additional parameters by throwing with an object. For example, if you include the statusCode parameter, it will be used as the HTTP response status code that is returned when calling the behavior.
try {
//Do something
} catch (e) {
throw {
statusCode: 422,
message: 'Failed to do something'
};
}