Last active
November 2, 2020 17:31
-
-
Save janbaer/f9a8a109f59a95904fdb8b00131b9e03 to your computer and use it in GitHub Desktop.
JavaScript improved error handling
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
const os = require('os'); | |
class ServerError extends Error { | |
constructor(message, innerError) { | |
super(); | |
this.name = this.constructor.name; | |
this.innerError = innerError; | |
// Borrowed from: https://stackoverflow.com/questions/35392675/how-to-override-error-stack-getter | |
Object.defineProperty(this, 'message', { | |
get: () => { | |
if (this.innerError) { | |
return `${this._message}: ${this.innerError.name} - ${this.innerError.message}`; | |
} | |
return this._message; | |
}, | |
set: value => this._message = value | |
}); | |
this.message = message; | |
Object.defineProperty(this, 'stack', { | |
get: () => { | |
const lines = (this.innerError ? this.innerError.stack : this._stack).split(os.EOL); | |
while (lines[0].startsWith('Error') || lines[0].startsWith(' at new ')) { | |
lines.splice(0, 1); | |
} | |
return lines.join(os.EOL); | |
}, | |
set: value => this._stack = value | |
}); | |
this.stack = new Error().stack; | |
} | |
} | |
class DatabaseError extends ServerError { | |
} | |
function dbFunction() { | |
try { | |
throw new Error('Mongo was throwing an error'); | |
} catch (err) { | |
throw new DatabaseError('Unexpected error while doing something with the database.', err); | |
} | |
} | |
function callDbFunction() { | |
try { | |
dbFunction(); | |
} catch (err) { | |
throw new ServerError('Something went wrong in the server', err); | |
} | |
} | |
function letsThrowNormalError() { | |
throw new Error('This is a simple error'); | |
} | |
function handleAnyError() { | |
try { | |
letsThrowNormalError(); | |
} catch (err) { | |
throw new ServerError('A normal error occurred', err); | |
} | |
} | |
function serverFunction() { | |
throw new ServerError('Our server won\'t work anymore.'); | |
} | |
try { | |
callDbFunction(); | |
// handleAnyError(); | |
// serverFunction(); | |
} catch (err) { | |
console.error(err.name, err.message, os.EOL, err.stack); | |
// console.log(err); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment