Skip to content

Instantly share code, notes, and snippets.

@jrichardsz
Last active August 19, 2022 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrichardsz/9045c2ca94c3fc5b5acec9282272d475 to your computer and use it in GitHub Desktop.
Save jrichardsz/9045c2ca94c3fc5b5acec9282272d475 to your computer and use it in GitHub Desktop.
re throw error

CustomError.js

function CustomError(message, code, error) {
    this.constructor.prototype.__proto__ = Error.prototype
    this.code = code
    this.message = message
    if (error) {
        Error.captureStackTrace(error);
    }else{
        Error.captureStackTrace(this, this.constructor);
    }
}

module.exports = CustomError;

throw

this.getAccessToken = async(code) => {

    if (typeof code === "undefined") {
        throw new CustomError("code is required to get the microsoft oauth2 access_token", 
            ApiResponseCodes.missing_system_configuration.code);
    }

stacktrace

  MicrosoftLoginService : getAccessToken
8/19/2022, 12:38:18 PM  INFO CustomError: code is required to get the microsoft oauth2 access_token
    at MicrosoftLoginService.getAccessToken (/foo/bar/my-api/src/main/node/services/MicrosoftLoginService.js:74:19)
    at Context.<anonymous> (/foo/bar/my-api/src/test/node/services/MicrosoftLoginService/MicrosoftLoginService.test.js:182:41)
    at callFn (/foo/bar/my-api/node_modules/mocha/lib/runnable.js:358:21)
    at Test.Runnable.run (/foo/bar/my-api/node_modules/mocha/lib/runnable.js:346:5)
    at Runner.runTest (/foo/bar/my-api/node_modules/mocha/lib/runner.js:621:10)
    at /foo/bar/my-api/node_modules/mocha/lib/runner.js:745:12
    at next (/foo/bar/my-api/node_modules/mocha/lib/runner.js:538:14)
    at /foo/bar/my-api/node_modules/mocha/lib/runner.js:548:7
    at next (/foo/bar/my-api/node_modules/mocha/lib/runner.js:430:14)
    at Immediate.<anonymous> (/foo/bar/my-api/node_modules/mocha/lib/runner.js:516:5)
    at processImmediate (node:internal/timers:466:21) {
  code: 500110
}

source: https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript

class RethrownError extends Error {
constructor(message, error){
super(message)
this.name = this.constructor.name
if (!error) throw new Error('RethrownError requires a message and error')
this.original_error = error
this.stack_before_rethrow = this.stack
const message_lines = (this.message.match(/\n/g)||[]).length + 1
this.stack = this.stack.split('\n').slice(0, message_lines+1).join('\n') + '\n' +
error.stack
}
}
throw new RethrownError(`Oh no a "${error.message}" error`, error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment