Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing object to node's Error class returns an unaccessible object

Tags:

node.js

v8

I'm returning an Error object, to which I pass an object (instead of a simple message):

if (err) {
   return myCallback(new Error({
      error_code: 'sample_machine_readable_code', 
      error_message: 'There is an error in the response from the service.', 
      error: err
   }));
}

And the result in the console is [Error: [object Object]]. I tried accessing its properties both as properties of an array and as an object, but always end up with undefined. JSON.stringify-ing it returns an empty object {}. By "accessing" I mean trying to log the error, f.e. with console.log(err); (which ends up in [object Object]) or err.message or err.Error, or err['Error'], but these were undefined.

I was reading through Node's Error class docs and it seemed like it's okay to pass objects. Am I mistaken? Should I just return a simple custom-constructed object instead of a new Error? Like that:

if (err) {
       return myCallback({
          error_code: 'sample_machine_readable_code', 
          error_message: 'There is an error in the response from the service.', 
          error: err
       });
    }

Cuz I just wanted to use more of what Node offers and to stick to some widely used convention instead of going "my own way".

like image 529
Milkncookiez Avatar asked Feb 19 '16 10:02

Milkncookiez


People also ask

What is node error?

An error in Node. js is any instance of the Error object. Common examples include built-in error classes, such as ReferenceError , RangeError , TypeError , URIError , EvalError , and SyntaxError .


1 Answers

What you can do, is simply create an instance of Error and assign custom properties to it, like this:

var error = new Error("There is an error in the response from the service"); 
error.error = err; 
error.error_code = "sample_machine_readable_code"

return myCallback(error);
like image 104
Vsevolod Goloviznin Avatar answered Sep 23 '22 22:09

Vsevolod Goloviznin