sac Dahal sac Dahal - 2 months ago 14
Javascript Question

Error sending error to client side in nodeJs

I am using async in nodeJS, and in my final callback I am handling the error and trying to send it back to my angular controller.

function (err, data) {
if (err) {
console.log(err);
res.status(500).send({ err : err});
}
else {
res.json({data: data});
}
});


Now the error in the console is.

[Error: Username is already in use]


I am not able to get this particular error in my angular controller I tried sending the error in all combinations such as .

res.status(500).send({ err : err[0]});
res.status(500).send({ err : err.Error});


This is what I get in my front end.

Object {data: Object, status: 500, config: Object, statusText: "Internal Server Error"}
config
:
Object
data
:
Object
err
:
Object
__proto__
:
Object
__proto__
:
Object
headers
:
(d)
status
:
500
statusText
:
"Internal Server Error"


How can I bring that username in use error to my front End.

Answer

500 errors are usually reserved for Server errors, and not for scenarios like the one you have described. Server errors should be handled by your server and elegantly presented to your front end. Client errors should be in the 400s. Why don't you try a 409 or a 400:

res.status(409).json({error: "Username already exists");

Look at HTTP Status codes for more:

409 Conflict The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

Note: Also, as a good practice, make sure you return your res. functions, for predictable flow of control, like so:

return res.status(409).json({error: "Username already exists");