About
This page is about exception in Javascript
Exceptions can be caught:
- in a try, catch, throw, finally statement.
Example
With the error object
try {
throw new Error('Badddd')
} catch (e) {
if (e instanceof Error) {
// you should use `console.error`
console.log(e.name + ': ' + e.message + ". Stack Trace" + e.stack)
}
}
With a string
You can also throw a string. You don't get extra information such as the stack trace but it's possible.
try {
throw 'Badddd'
} catch (e) {
console.log(e);
}
Syntax
The interface of an error is
interface Error {
name: string;
message: string;
stack?: string;
}
How to create another Exception Type?
export class SessionError extends Error {
}
throw new SessionError('Yolo');
Management
Pause
type (instanceof)
Javascript - instanceof An error is an object, to discover the instance, just output the prototype name
try {
// an error occured
} catch (e){
console.log("The instance of the error is "+e.__proto__.toString()); // To get the instance of name
// if e.__proto__.toString() ==> SyntaxError
if (e instance SyntaxError) {
//... Do whatever
}
}
Variable scope
The try…catch binds a caught exception to a variable that is scoped just to the catch block (not on the function level). This is the only scope exception.
var foo = "initial value";
try {
throw "exception";
} catch (foo) { // < -- The local variable foo is a caught exception and will not affect the local variable because its scope is limited to the try catch block
foo = "exception"; // <-- This change is only for the try block
}
console.log("The foo variable was not polluted when declared as a caught exception\n"+
"foo will still have its initial value");
console.log(foo);
Caugth with Google Analytics
See https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions