Skip to content

Instantly share code, notes, and snippets.

@Xotabu4
Created March 21, 2019 10:11
Show Gist options
  • Save Xotabu4/b98cec5664e8696d8220d7774ea34705 to your computer and use it in GitHub Desktop.
Save Xotabu4/b98cec5664e8696d8220d7774ea34705 to your computer and use it in GitHub Desktop.
// Call stack is whole tree of nested function calls
function A() {
return B();
}
function B() {
return C();
}
function C() {
return D();
}
function D() {
return "data";
}
// uncomment
// console.log(A());
// **************************************************************************************************
// Lets track how error propagates thru callstack:
function A() {
try {
return B();
} catch (err) {
console.log(err.stack);
}
}
function B() {
return C();
}
function C() {
return D();
}
function D() {
return error
}
console.log(A());
// Working with try/catch for errors
try {
console.log("Start of try runs");
nonvariable; // error, variable is not defined!
console.log("End of try (never reached)"); // try block interupted, so this never be executed
} catch (error) {
console.log(`Error has occured!`);
}
console.log("...Then the execution continues");
// try..catch only works for runtime errors
// JS engine can't read this code, so cannot run
/* commented
try {
&*()
} catch(e) {
// JS cannot catch syntax errors!
}
*/
// ***************************************************************************
// Default error object structure
try {
nonvariable; // error, variable is not defined!
} catch (err) {
console.log(err.name); // ReferenceError
console.log(err.message); // nonvariable is not defined
console.log(err.stack); // callstack with functions calls
// Can also show an error as a whole
// The error is converted to string as "name: message"
console.log("Error obj", err); // ReferenceError: nonvariable is not defined
}
// ***************************************************************************
// Rethrowing
function parseUser(json) {
try {
return JSON.parse(json);
} catch (err) {
console.log("parseUser got error: ", err.message);
throw err;
}
}
parseUser("not a json");
// Use if/else to handle only errors that you know how to handle, and rethrow all others
function parseUser(json) {
try {
return JSON.parse(json);
} catch (err) {
if (err.name == "SyntaxError") {
console.log("JSON Error: " + err.message);
} else {
console.log(err)
// Rethrowing everything except SyntaxError
throw err;
}
}
}
parseUser("not a json");
// ***************************************************************************
// Throwing our own errors
function parseUser(json) {
let user = JSON.parse(json);
if (!user.name) {
throw new SyntaxError("Incomplete data: no name");
}
return user;
}
parseUser('{ "age": 30 }');
// It is strongly recommended to throw Error-compatible objects (with name, message, stack)
// For example:
// throw {name: 'MyNiceError', message: 'Some nice description of what happened'}
// But actually you can throw anyghing, this is valid, but mostly useless
// throw true;
let myError = new Error()
myError.name = 'OwnError'
myError.message = 'Some nice message'
throw myError
// try/catch/finally
try {
console.log("try");
if (confirm("Make an error?")) {
BAD_CODE();
}
} catch (e) {
console.log("catch");
} finally {
console.log("finally");
}
// Finally block gets executed in ANY case - no matter error was or not
// finally and return
// What this code will print?
function finallyAndReturn() {
try {
return 1;
} catch (error) {
console.log(error);
} finally {
return 2;
}
}
let res = finallyAndReturn();
console.log(res); // 2
/**
Since finally executed AFTER try in ANY case,
return from finally will overwrite try/catch block return
*/
function catchAndReturn() {
try {
return 1;
} catch (error) {
return 2;
} finally {
return 3;
}
}
let res = finallyAndReturn();
console.log(res); // 3
// Same here - finally replaces value of all other previous returns
// Use finally to correctly close database connections, write logs,
// Try can be used without catch
try {
nondef;
} finally {
console.log("i still work!");
}
// In this case error will be thrown outside, but finally will be executed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment