Node domains on Azure Mobile Services - node.js

I can't seem to get domains to work on Azure Mobile Services (ZUMO). For example:
var myDomain = require('domain').create();
myDomain.on('error', function ()
{
console.log('got here');
});
myDomain.run(function() {
boo(); //throws
});
The on error handler of my domain will never get called. This exception will be caught by ZUMO and their 500 error will get returned. I'd prefer to trap the exception myself, log it, and return a 500 using my preferred JSON format. I realize that there is some global error trapping that ZUMO is doing but I would think that if I have a domain it should catch it before it bubbles up to the ZUMO wrapper. Any suggestions?
(ZUMO runs on Node 0.8.28)

The code you list will handle uncaught exceptions. Mobile Services scripts and the underlying async data operations are wrapped in try..catch blocks, so they will not invoke a domain error handler.
You should be handling errors in your scripts using normal error handling practices, i.e. try..catch blocks or error handling callbacks for promises. You can then return the appropriate response using res.send.

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'})
})

Azure Function hangs on error

If you have a error in code and did not callback, Azure Function just hangs.
AWS by default detects for empty loop and exits the lambda and logs the error, return the call to the caller with 5xx. It can also be controlled with callbackWaitsForEmptyEventLoop = false.
Is there is anything in Azure Functions that we can control how the function should exist in case of unhandled exceptions.
This currently isn't supported on Azure Functions.
It's the first I've heard this request, but it's a good idea. If you open a GitHub issue for it, I can take a look. (I'm the dev responsible for Node.js on Azure Functions) https://github.com/Azure/azure-functions
If you are using Azure Functions beta instead of using callbacks you may also export your functions as async which should allow the node worker to handle the exception without further intervention.
When exporting async functions calling the callback is redundant, and unnecessary.
Example:
module.exports = async function (context, req) {
throw new Error('Error')
}
Returns:
Request URL:http://localhost:7071/api/HttpTriggerJS
Request Method:GET
Status Code:500 Internal Server Error
Remote Address:[::1]:7071
Referrer Policy:no-referrer-when-downgrade

Meteor - How to handle external API connection errors?

I'm using a few external API's (some in timers, every minute or so) and sometimes I get some connection errors because of network problems or because the external systems are down for some reason. When I get this errors, the app restarts, and if the error persists the app continues restarting.
Any ideas on how can I ignore the connection error and keep the app running?
Code Example:
try {
var req = https.request(options, callback);
req.write(JSON.stringify(params));
req.end();
} catch (e) {
throw e;
}
Based on your code example. You're doing throw e inside your try catch. Essentially, you're catching an error and then throwing the error. Just do console.error(err) or however you want to handle that error, without throwing. This is what will cause your instance to stop.

setTimeout never calls when exception is thrown in different context

Using node.js, when I run the program
setTimeout(() => console.log("Timed out"), 0);
console.log("finishing");
I see
finishing
Timed out
But when I add a throw before "finishing"
setTimeout(() => console.log("Timed out"), 0);
throw new Error();
console.log("finishing");
I see
throw new Error();
^
Error
at Object.<anonymous> ...(stack trace here)...
And I don't see any mention of "Timed out".
Why is that? Even though the initial context would throw, once the stack was freed up, I expected the callback I passed to setTimeout would still run.
Does having an uncaught exception cause all timeouts to get canceled? Is this feature documented somewhere?
If I have multiple timeouts, is there a way for me to make sure that all the other timeouts continue to run when they can even if one of them happens to throw?
Unlike a web application running on browser, a Node application runs as a process on top of Google V8 JavaScript Engine. If you look into https://nodejs.org/api/timers.html is states that
The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.
As the above statement explains, even though the same global functions are available in both cases, their implementations are different. Therefore when an uncaught exception occurs in a Node application, all code related to timeouts will stop as the process is terminated. The best way to handle this is to properly handle all exceptions. You can use the below code to capture all uncaught exceptions from the process level itself.
process.on('uncaughtException', function(error) {
console.log(error);
});

How to Handle Errors in Node.js using Express

I am working with a partner on a project. He has written a lot of code in Node.js+Express, but we've been running into issues with the architecture.
To remedy this, my primary role has been to figure out the best way to architect a Node.js+Express application. I've run into two scenarios, dealing with errors, and I'd like some suggestions.
First, how do I capture top-level exceptions? The last thing I want is for a bug to completely kill the node process. I want to continue serving users in the face of any error.
Secondly, some errors are passed back via callbacks (we're using caolan / async). As part of each route handler, either we render a view (GET), redirect to another route (POST) and we want to redirect to an error screen with a custom error message. How can I make sure to capture this logic in one place?
First, how do I capture top-level exceptions? The last thing I want is for a bug to completely kill the node process. I want to continue serving users in the face of any error.
Edit: I think node's philosophy in general is that any uncaught exceptions should kill the process, and that you should run your node app under some kind of process monitor with appropriate logging facilities. The following advice is regarding any other errors you might encounter in your express route handlers etc.
Express has a general errorHandler, which should capture all thrown errors as well as everything passed as a parameter to next in your routes/middlewares, and respond with 500 Internal Server Error.
Secondly, some errors are passed back via callbacks (we're using caolan / async). As part of each route handler, either we render a view (GET), redirect to another route (POST) and we want to redirect to an error screen with a custom error message. How can I make sure to capture this logic in one place?
You could create a custom handleError, which you call in each callback like so:
async.series(..., function(err, results) {
if(err)
return handleError(req, res, err);
// ...
});
Or you could just pass the errors on with next(err) and implement your custom error handler as described here: http://expressjs.com/guide/error-handling.html
Top level exceptions:
You can use the uncaughtException event from process, but it's generally not recommended.
Often applications will go into a corrupted state (eg. you have some state which typically gets set, but the exception caused that not to happen) when an exception is thrown. Then, it will just cause more and more errors from there on onwards.
A recommended approach is to use something like forever to automatically restart the app in case it crashes. This way you will have the application in a sane state even after a crash.
Error handling in express:
You can create a new Error instance and pass it to the next callback in the chain.
Eg.
express.get('/some/url', function(req, res, next) {
//something here
if(error) {
next(new Error('blah blah'));
}
});
To handle the error from here on onwards, you can set an error handler. See express docs on error handling
Checkout the excellent log-handling module Winston: https://github.com/flatiron/winston
It allows you to configure exception handling in a manner that will not only log it, but will allow the process to continue. And, since these would obviously be serious issues, you can even configure Winston to send out emails on specific event types (like exceptions).

Resources