Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the best way to expose and compose errors in Node.js?
    text
    copied!<p>I'm writing a module that talks to a REST API, and since the REST API provides nice, semantic error responses (e.g. 403 vs. 503), I want to convey those semantic errors to callers.</p> <p>(Edit: what I mean by that is, the caller should be able to programmatically understand the cause of the error and act accordingly, e.g. display the appropriate UI.)</p> <p>What's the best way for me to do so?</p> <ol> <li><p>Create my own <code>Error</code> subclasses for those semantics, e.g. <code>mymodule.ForbiddenError</code>, <code>mymodule.ServiceUnavailableError</code>? Callers would then check <code>instanceof</code> to derive semantics. This is most typical in statically-typed languages like C# and Java.</p></li> <li><p>Add e.g. a <code>mymoduleCode</code> property to standard <code>Error</code> instances, with semantic strings like <code>'Forbidden'</code> or <code>'ServiceUnavailable'</code>. Node.js itself does this, e.g. <code>code: 'ECONNREFUSED'</code>.</p></li> <li><p>Some other way?</p></li> </ol> <p>==</p> <p>I'm writing another module now, that wraps the first module. I don't want to expose the internal module's errors directly, but it'd be nice to compose/wrap them, for debuggability.</p> <p>What's again the best way for me to do so?</p> <ol> <li><p>Add e.g. an <code>internalError</code> property to my <code>Error</code> instances that references the internal module's <code>Error</code> instance. Again C# and Java do this. (<a href="http://msdn.microsoft.com/en-us/library/system.exception.innerexception%28v=vs.110%29.aspx">Exception#InnerException</a> / <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Throwable.html#getCause%28%29">Throwable#cause</a>)</p></li> <li><p>Some other way?</p></li> </ol> <p>Most tooling I've seen, though, only displays the <code>stack</code> property of <code>Error</code> instances, so this data would get lost in those cases. Is there a typical/conventional way that already exists?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload