Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain exceptions in javascript (ie add cause like in java)

Is there a standard / best practice way to add a cause of an exception in javascript. In java you might do this:

Throwable t = new Exception("whatever"); t.addCause(previouslyCaughtException); throw t; 

When the resulting exception is printed, it'll give you a nice trace that includes causes. Is there any good way to do this in javascript or do I have to roll my own?

like image 693
B T Avatar asked Jul 26 '13 16:07

B T


1 Answers

For now (until there's a better answer), this is what I've done:

... } catch(e) {   throw new Error("My error message, caused by: "+e.stack+"\n ------The above causes:-----") } 

The way I'm printing exceptions makes it nice and clean looking:

console.log(e.stack) 

prints something like this:

My error message: SomeError <some line> <more lines> ------The above causes:----- <some line> <more lines> 

The line might be better if it said "causes" because the stack trace of the exception causing the error is printed first.

like image 65
B T Avatar answered Sep 20 '22 15:09

B T