How to handle errors in node.js - node.js

I know that in node, I can use process.on('UncaughtException',evtHandlerFunction(){/*code*/}); but how do I go about handling errors "properly"? Like, whenever there's an error, send out a status code 500 on the current response stream of the request that the error occured when responding to and tell the user there was a problem. But I can't seem to figure out a good way to do this. How would I go about figuring out what the "current response stream" is, for example? I just want a concept of how to do this, I don't necessarily need code. Sorry if I was unclear, please post a comment if you don't understand.

it totally depends on what kind of errors u want to handle.....
server errors can be http errors, socket errors, net errors etc.
each of these modules have an error handling code
eg:
a socket server object has:
socket.on('error',function(err)
{
//code to handle
});
check out the detailed doc on site nodejs.org

then u can use the response object as:
response.writeHead('500',{'Content_type':'text/plain'});
response.end('Your Error Message');
'your error message' will be the responseText for the client browser

Related

How to show the error alerts on UI whenever the catch error or console error comes and the server stops in localhost or in production side (heroku)?

I want a solution for how I can write the code in nodejs so that whenever console error occurs I want to send the alert erros on UI sid to the user so that he can go back or refresh or login again instead of blocking the page/ website in between whenever the application error logs comes in heroku.
Please provide me a solution for this!!!
Thanks!
Edit:
I am asking for general only. Means just like I was testing my web app on heroku after making live and in between while testing an error occured and I got redirected to the heroku application error log page like this below. So I just want to ignore this and instead of this an alert should appear telling the user to go back or login again as some error occured. but not to break the page in between like this.
:(
The server can't send the response to the client if it crashes completely. When a server crashes it means that your code is not handling the error properly.
As you didn't specify which programming language or framework you are using. I assume that it is Node.js as you mentioned .catch()
In this case, you should have a try/catch block in your code or a .catch if you are using promises. The error occurred but the server won't just crash completly.
You will need to have something similar as below in your route handlers:
Async/Await:
try{
// Do stuff
}catch(err){ // Bad things happen
// Log the error so you know what went wrong
console.log(err)
// Send the error response to the frontend
res.status(500).json({msg:'Server Error'})
}
Promises:
something
.then(//Do stuff)
.catch(err => { // Bad things happened
console.log(err)
// Send the error response to the frontend
res.status(500).json({msg:'Server Error'})
})

Server Side JS SDK fails to flag user

I have a webhook that runs on message save and message update. I do some basic bad word filtering. I can update the message to filter out bad words. However, when I attempt to flag the message, I get an error. Has anyone seen anything like this? How have you worked around it?
The code:
client.flagMessage(message.id).then(r => console.log('flagged message', r))
I have verified that client works as I am able to update the message with client in the same Promise.all() call.
The error:
Flag failed with error: "either user or user_id must be provided when using server side auth."
Version:
"stream-chat": "^1.7.4"
The docs:
https://getstream.io/chat/docs_rest/#flag
https://github.com/GetStream/stream-chat-js/blob/master/src/client.js#L1227
It seems very similar to this closed issue:
https://github.com/GetStream/stream-chat-js/issues/113
This might not be a proper answer but definitely is a resolution for your problem.
If setUser is called on the client then server will be able to get the flagging user from the JWT (client side auth) but in server side auth, there is no user passed to server so you get the expected error message.
You check REST docs and as seen, server supports it where JS client lacks this server side support. This a missing feature bug from JS client. It's reported to be extended as soon as possible.

Which HTTP status code to return when unable to save data in mongodb node.js?

I am learning Backend development using node.js and mongodb.
Mongoose has a method Model.save(function(err,model)) what status code must be returned when for some reason the document could not be saved.
In terms of code:
Model.save(function(err,model){
if(err)
res.status(5xx).send(err);
if(!model) {
//executed when unable to save document IMHO correct me I am wrong
res.status(xxx).send("Unable to save the model in database");
}
});
Well, this is a tricky question but I have to tell you 422 is not a valid state.
What I imagine is you are trying to say there was an error, it might be a network problem, service not ready (Mongo down, unresponsive) or similar. There is no 4xx code to represent that, if you want to use any 4xx it might not be representing the truth.
The usual response is 503 because it's unavailable which is what I imagine you want to communicate.
You could use any code which is represented by 4xx or 5xx.
Using 2xx or 3xx for reporting errors prevents error detection by http-aware softwares.
Moreover you can send a specific error message by using
JSON.stringify(error, undefined, 2);
checkout this link where I explained what this method does
https://stackoverflow.com/a/56773148/8284444

Why might a nodeJS API work locally but fail in production?

An API method I've been using without problems on localhost:3000/userinfo suddenly gives an "Empty Reply From Server" when I upload that same code to my web server and send a POST request to myserver.com:3000/userinfo.
Even more strange is that if the JSON returned by user info does not contain an array of objects, there is no error locally or remotely.
I don't know how much detail will be useful, and how much will just clutter this question. This one is especially strange so I'd like to approach it very generally. In other words, I don't think I'm missing a semi colon this time because the API function works perfectly when run on a local server.
So without a whole lot of detail, the only thing I can suggest here is make sure your ports are correct. You said 4200 locally but its 3000 on your server? The error you're getting also suggests ( I'm assuming cURL? ) that it couldn't connect at all to your server, which furthers my hypothesis.
Alternatively, there could be an error in your API and its "crashing" without logging anything, which would also cause an empty reply error.
Be sure to capture unhandled exceptions using process events to log out errors!
https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_events
process.on('uncaughtException', function (error) {
console.error("GOT UNCAUGHT EXECPTION!", error)
process.exit(1);
})

Detecting Socket.IO message delivery error on client side

We need to update the client side UI to indicate that a message fails to deliver. How do I have Socket.IO JS client call a custom callback directly when the message fails to deliver? For example, something like:
socket.emit("event", data).onError(myCallback);
I know Socket.IO provides the Ack mechanism to confirm delivery success. Therefore, one can set up a timer with a handler which calls the failure callback, if the ack is not called after a certain amount of time. But this doesn't seem to be the best way to do.
Also there is the error event provided by Socket.IO, but it doesn't come with info regarding which emit caused the error.
Unfortunately there's no way to get errors from callbacks, the only way is to indeed create your own timeout:
var timeoutId = setTimeout(timeoutErrorFn, 500);
var acknCallbackFn = function(err, userData){
clearTimeout(timeoutId)
//manage UserData
}
socket.emit('getUserData', acknCallbackFn);
Source of the code
And there's another issue about this, open
So for the time being you have to stick with your manual setTimeout.

Resources