Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

educate people on how to add custom exceptions #324

Closed
kevinburkeshyp opened this issue Mar 3, 2015 · 4 comments
Closed

educate people on how to add custom exceptions #324

kevinburkeshyp opened this issue Mar 3, 2015 · 4 comments

Comments

@kevinburkeshyp
Copy link

So, borrowed from somewhere on the Internet, we were doing custom exceptions that looked something like this:

var ValueError;

ValueError = (function() {
  function ValueError() {}
  ValueError.prototype = Object.create(Error.prototype);
  return ValueError;
})();

module.exports = ValueError;

Unfortunately if you call sentry.client.captureError(new ValueError("foobar")), Sentry doesn't have the stack trace.

Instead you want something like this

var ValueError;

ValueError = (function() {
  function ValueError(message) {
    this.message = message;
    this.stack = new Error(this.message).stack;
  }
  ValueError.prototype = Object.create(Error.prototype);
  return ValueError;
})();

module.exports = ValueError;

It's pretty hacky (well, subclassing exceptions in general is a shit show), but creating a fake error and copying the stack will set the stack trace properly.

Was thinking raven could take the lead here and actually document the right way to create/subclass exceptions so this kind of data doesn't get lost / your Sentry data is more useful.

@mattrobenolt
Copy link
Contributor

The best way I've seen is the way I do it inside raven.js: https://github.com/getsentry/raven-js/blob/master/src/raven.js#L381-L386

Not sure the pros/cons though. :)

@mattrobenolt
Copy link
Contributor

fwiw, I think doing this.stack = new Error(this.message).stack is not the best. You're also not carrying over the name. Also, the stack attribute is typically lazily evaluated. So by initializing it here, you're forcing it to be evaluated. And lastly, this will add an extra frame to your stack trace.

@askaliuk
Copy link

askaliuk commented Oct 4, 2016

Useful. +1

@kamilogorek
Copy link
Contributor

There's a great post on how to achieve it: https://coderwall.com/p/m3-cqw/subclassing-error-in-javascript-is-harder-than-it-seems

I don't think we will add this to our docs anytime soon, so closing it for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants