Answer the question
In order to leave comments, you need to log in
Error handling during asynchronous execution in JavaScript?
When executing code synchronously, exceptions are a very convenient error handling mechanism. But in JavaScript, there is a lot of code that runs asynchronously - for example, requests to the server. Often, callbacks are used to handle errors in this case, but in terms of convenience, this technique cannot be compared with exceptions, in which the call stack independently unwinds to the place of interception.
I searched long and hard for something on this topic, but found only something like this:
try {
helloWorld();
}
catch (e) {
alert(e.message);
}
function helloWorld() {
throw new Error('Hello world!');
}
Answer the question
In order to leave comments, you need to log in
An asynchronous function is therefore asynchronous because the return from it (return) occurs much faster than the source code of the operations and callbacks launched from inside it finishes executing.
Therefore, it is useless to wrap such a function in a
For such a transfer, as a rule, the first parameter of the
The reason for this order, in which the error parameter comes first in a row, is that instead of "throw new Error()", a simple
To comply with this order, inside such a
I do not share the opinion
And this is not only my opinion: I already noticed in January of this year (2012) that the async package was among the ten most used modules for the Node engine according to The Node Toolbox website, based on the statistics of the npm package manager.
Not exactly an answer to the question, but I personally prefer console.log() instead of alert()
stackoverflow.com/questions/3677783/is-it-possible-to-catch-exceptions-thrown-in-a-javascript-async-callback
stackoverflow.com/questions/6620207/how-to-easily-handle-all-errors -in-asynchronous-functions-of-javascript The
easiest way is to wrap the contents of each function that is called asynchronously in a try/catch.
For asynchronous calls, functions are written in a chain in the form:
callFunction(function() { /* async code */ }).then(function() { /* async code */ }).then(function(){ /* async code */ }).onError(function() { /* error handler */ });
Such a function organizes the order of execution and error handling itself. There are some libraries out there for this, but I'm sure they're all crooked, poorly made, and overbloated, so it's better to write your own code for that.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question