Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an Error object in node js to a string properly?

This error throws up whenever I enter a duplicate entry in mysql.

{ [Error: ER_DUP_ENTRY: Duplicate entry '[email protected]' for key 'email '] code: 'ER_DUP_ENTRY', errno: 1062, sqlState: '23000', index: 0 }

What I want to do is turn this Error object into a string. I tried using JSON.stringify() and when I printed it on the console, only the last part got converted into a string :

{"code":"ER_DUP_ENTRY","errno":1062,"sqlState":"23000","index":0}

I need to convert the first part as well of the error, the one inside the [ ] so that I am able to diagnose duplicates properly. How do I retrieve that part whenever I convert an Error object into a string?

like image 236
dtem052996 Avatar asked Mar 13 '16 23:03

dtem052996


People also ask

How do you turn an object into a string in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);


2 Answers

I thought I had to use JSON for this problem because of the way the Error object was formatted. How I solved this one was just to use

err.toString()
like image 142
dtem052996 Avatar answered Oct 02 '22 05:10

dtem052996


To get the full stack use stack property of the Error object:

console.log(error.stack)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack

like image 25
Evandro Pomatti Avatar answered Oct 02 '22 05:10

Evandro Pomatti