try catch not always works in iced coffee script - error-handling

I use try catch block in iced coffee script. I call not existent method fake of not existent object a and expect to catch error.
db = require '../../call/db.iced'
try
await db.find "79", defer c, d
a.fake()
catch error
console.log "error catched"
console.log error
But after calling function db.find a.fake() throw error in console, but it don't use try catch block as expected.
If I comment out string await db.find "79", defer c, d...
db = require '../../call/db.iced'
try
# await db.find "79", defer c, d ############## commented out
a.fake()
catch error
console.log "error catched"
console.log error
... it works as expected and error is catched.
I tried to change string await db.find "79", defer c, d by other simple async functions calles but they works fine and error was catched well.
It is interesting that function db.find works good. When I comment out string a.fake()...
db = require '../../call/db.iced'
try
await db.find "79", defer c, d
#a.fake() ################################ commented out
catch error
console.log "error catched"
console.log error
... this script works without any errors and so without catching errors.
Can not figure out why I can not catch error after function await db.find "79", defer c, d.

The documentation states the following on try catch statements:
The only exception is try, which doesn't catch exceptions when called
from event handlers the main loop, for the same reason hand-rolled
asynchronous code and try do not work well together.
I suspect that since db.find is called asynchronously, the try construct remains with the db.find thread and does not stay in the main thread. This would result in the findings you describe.
One crude solution is to catch both function calls. However, I think the proper way to use await is with the defer function. Check out the documentation for an explanation.
Also, you might find the following helpful:
How to correctly handle errors with IcedCoffeeScript?
Possible Solutions
Place a try catch around both statements.
try
await db.find "79", defer c, d
catch error
console.log "error catched"
console.log error
try
a.fake()
catch error
console.log "error catched"
console.log error
As described in the link above, place db.find outside the try catch and detect it's error another way.
await db.find "79", defer err, id
if err then return cb err, null
try
a.fake()
catch error
console.log "error catched"
console.log error

Related

MySQL2 Library NodeJS - Update Fails without error & RowsAffected on async call

The way to get AffectedRows when non-Async is shown here: https://github.com/mysqljs/mysql/issues/363
My Code below - none of the console.logs after the update display in the console, certain columns are not being updated in the database, and no error or try catch is encountered. If there's an error, why don't I see it, otherwise, why don't I see the AffectedRows?
This is being called from another async function.
async function UpdatePassword(connection, rowID) {
... some code omitted here...
try
{
var [errQuery,results] = await
connection.query(sqlUpdate);
if (errQuery) throw errQuery;
console.log("Back from update");
console.log("AffectedRows=" + results.affectedRows);
} catch (err)
{
console.log("*** Catch Error:")
console.log(err.stack);
}
}
I think I have improved the code, but same issue. Non error, no console.log statements after the connection.query show up.
console.log("SQL Update=" + sqlUpdate);
try
{
var [rows, fields, errQuery] = await connection.query(sqlUpdate);
if (errQuery) throw errQuery;
console.log("Back from update");
console.log("AffectedRows=" + rows.affectedRows);
} catch (err2)
{
console.log("*** Catch Error:")
console.log(err2.stack);
}
console.log ("end function");
Got the answer here: https://github.com/sidorares/node-mysql2/issues/999.
The call from the first async routine to the second one needed an await.
for (let r=0; r < rows.length; ++r) {
await UpdatePassword(connection, rows[r].ID);
}
He recommended a for loop, instead of answer I got earlier here. If using .each or .map, you create another "inner" function, which is not async, and you can't call use the "await" keyword in that kind of logic.

Parse Promises in Cloud Code / Express.js [duplicate]

I had a look at the bluebird promise FAQ, in which it mentions that .then(success, fail) is an antipattern. I don't quite understand its explanation as for the try and catch.
What's wrong with the following?
some_promise_call()
.then(function(res) { logger.log(res) }, function(err) { logger.log(err) })
It seems that the example is suggesting the following to be the correct way.
some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })
What's the difference?
What's the difference?
The .then() call will return a promise that will be rejected in case the callback throws an error. This means, when your success logger fails, the error would be passed to the following .catch() callback, but not to the fail callback that goes alongside success.
Here's a control flow diagram:
To express it in synchronous code:
// some_promise_call().then(logger.log, logger.log)
then: {
try {
var results = some_call();
} catch(e) {
logger.log(e);
break then;
} // else
logger.log(results);
}
The second log (which is like the first argument to .then()) will only be executed in the case that no exception happened. The labelled block and the break statement feel a bit odd, this is actually what python has try-except-else for (recommended reading!).
// some_promise_call().then(logger.log).catch(logger.log)
try {
var results = some_call();
logger.log(results);
} catch(e) {
logger.log(e);
}
The catch logger will also handle exceptions from the success logger call.
So much for the difference.
I don't quite understand its explanation as for the try and catch
The argument is that usually, you want to catch errors in every step of the processing and that you shouldn't use it in chains. The expectation is that you only have one final handler which handles all errors - while, when you use the "antipattern", errors in some of the then-callbacks are not handled.
However, this pattern is actually very useful: When you want to handle errors that happened in exactly this step, and you want to do something entirely different when no error happened - i.e. when the error is unrecoverable. Be aware that this is branching your control flow. Of course, this is sometimes desired.
What's wrong with the following?
some_promise_call()
.then(function(res) { logger.log(res) }, function(err) { logger.log(err) })
That you had to repeat your callback. You rather want
some_promise_call()
.catch(function(e) {
return e; // it's OK, we'll just log it
})
.done(function(res) {
logger.log(res);
});
You also might consider using .finally() for this.
The two aren't quite identical. The difference is that the first example won't catch an exception that's thrown in your success handler. So if your method should only ever return resolved promises, as is often the case, you need a trailing catch handler (or yet another then with an empty success parameter). Sure, it may be that your then handler doesn't do anything that might potentially fail, in which case using one 2-parameter then could be fine.
But I believe the point of the text you linked to is that then is mostly useful versus callbacks in its ability to chain a bunch of asynchronous steps, and when you actually do this, the 2-parameter form of then subtly doesn't behave quite as expected, for the above reason. It's particularly counterintuitive when used mid-chain.
As someone who's done a lot of complex async stuff and bumped into corners like this more than I care to admit, I really recommend avoiding this anti-pattern and going with the separate handler approach.
By looking at advantages and disadvantages of both we can make a calculated guess as to which is appropriate for the situation.
These are the two main approaches to implementing promises. Both have it's pluses and minus
Catch Approach
some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })
Advantages
All errors are handled by one catch block.
Even catches any exception in the then block.
Chaining of multiple success callbacks
Disadvantages
In case of chaining it becomes difficult to show different error messages.
Success/Error Approach
some_promise_call()
.then(function success(res) { logger.log(res) },
function error(err) { logger.log(err) })
Advantages
You get fine grained error control.
You can have common error handling function for various categories of errors like db error, 500 error etc.
Disavantages
You will still need another catch if you wish to handler errors thrown by the success callback
Simple explain:
In ES2018
When the catch method is called with argument onRejected, the
following steps are taken:
Let promise be the this value.
Return ? Invoke(promise, "then", « undefined, onRejected »).
that means:
promise.then(f1).catch(f2)
equals
promise.then(f1).then(undefiend, f2)
Using .then().catch() lets you enable Promise Chaining which is required to fulfil a workflow. You may need to read some information from database then you want to pass it to an async API then you want to manipulate the response. You may want to push the response back into the database. Handling all these workflows with your concept is doable but very hard to manage. The better solution will be then().then().then().then().catch() which receives all errors in just once catch and lets you keep the maintainability of the code.
Using then() and catch() helps chain success and failure handler on the promise.catch() works on promise returned by then(). It handles,
If promise was rejected. See #3 in the picture
If error occurred in success handler of then(), between line numbers 4 to 7 below. See #2.a in the picture
(Failure callback on then() does not handle this.)
If error occurred in failure handler of then(), line number 8 below. See #3.b in the picture.
1. let promiseRef: Promise = this. aTimetakingTask (false);
2. promiseRef
3. .then(
4. (result) => {
5. /* successfully, resolved promise.
6. Work on data here */
7. },
8. (error) => console.log(error)
9. )
10. .catch( (e) => {
11. /* successfully, resolved promise.
12. Work on data here */
13. });
Note: Many times, failure handler might not be defined if catch() is
written already.
EDIT: reject() result in invoking catch() only if the error
handler in then() is not defined. Notice #3 in the picture to
the catch(). It is invoked when handler in line# 8 and 9 are not
defined.
It makes sense because promise returned by then() does not have an error if a callback is taking care of it.
Instead of words, good example. Following code (if first promise resolved):
Promise.resolve()
.then
(
() => { throw new Error('Error occurs'); },
err => console.log('This error is caught:', err)
);
is identical to:
Promise.resolve()
.catch
(
err => console.log('This error is caught:', err)
)
.then
(
() => { throw new Error('Error occurs'); }
)
But with rejected first promise, this is not identical:
Promise.reject()
.then
(
() => { throw new Error('Error occurs'); },
err => console.log('This error is caught:', err)
);
Promise.reject()
.catch
(
err => console.log('This error is caught:', err)
)
.then
(
() => { throw new Error('Error occurs'); }
)

Handling Windows Store App exceptions from GetFileAsync

I have a problem with the following code example:
Windows::Storage::StorageFolder^ location = Package::Current->InstalledLocation;
try
{
task<StorageFile^> GetFileTask(location->GetFileAsync(sn));
GetFileTask.then([=](StorageFile^ file)
{
try
{
task<IBuffer^> ReadFileTask(FileIO::ReadBufferAsync(file));
ReadFileTask.then([=](IBuffer^ readBuffer)
{
// process file contents here
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
When using a filename that doesn't exist the function throws an exception:
Unhandled exception at 0x0FFCC531 (msvcr110d.dll) in GameTest2.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
I've been searching the internet and this exception breaks only when connected to the debugger. I'm using VS 2012. I've turned off all the relevant 'break on exception' but it still causes the debugger to break and non of my handlers are getting a chance to handle the exception.
If the file is missing I would expect the GetFileAsync method to throw a 'File doesn't exist' exception. Not sure why it keeps throwing the 'Invalid parameter' exception.
This is starting to bother me and I just can't find any known solution to this issue. Anyone have any ideas?
I'm going to try and change the method to not use the task<> code. Instead I'll call the GetFileAsync using 'await'. However I believe 'await' will just cause the calling thread to wait until the GetFileAsync has finished, which kind of defeats the point of asynchronous loading.
I'm wondering if this is a common issue with exception handling when using tasks.
Update:
OK, I've now found the solution:
task<StorageFile^>( location->GetFileAsync(sn)).then([](StorageFile^ openedFile)
{
return FileIO::ReadBufferAsync(openedFile);
}).then([](IBuffer^ readBuffer)
{
// Process file
}).then([](task<void> t)
{
try
{
t.get();
}
catch(Platform::Exception^ e)
{
// Handle error
}
});
It seems there needs to be an extra 'then' condition added to the end of the chain to pick up the exception.

SoapException Not Caught in try catch

Take the following try-catch statement in a WCF-Service
Try
'Here some method is being called.
Return myBs.PerformDailyUpdate()
Catch ex As Exception 'Exception is not being caught here
If service IsNot Nothing AndAlso service.HasWarnings Then
TextFileTracer.Write(String.Format("Warning in method: '{0}'.", name))
TextFileTracer.Write(service.GetWarnings)
End If
Try
TextFileTracer.Write("Error in dbmanager: " & service.HasErrors.ToString)
Catch ex2 As Exception
End Try
TextFileTracer.Write(String.Format("Error in method: '{0}'.", name))
TextFileTracer.Write(ex.Message & vbCrLf & ex.StackTrace)
End Try
End Function 'Exception shows here while debugging
In that method (PerformDailyUpdate) an ASMX-Webservice (.Net 2.0) is being called. This webservice throws occassionaly an SOAPException caused from a method being called from that webservice.yet somehow this SOAPException is nog being caught by the method above.
My Question: Why isn't the SOAPException being Caught? Are there some characteristics that seperates a SOAP-Exception from normal 'exceptions' generated (that in turn cause it not be caught)?
Note: The code written here is not mine. So Please don't judge me on it
ExceptionMessage (First part)
System.Web.Services.Protocols.SoapException: Unexpected application error: SqlException.
ADF.ExceptionHandling.GlobalExceptions.UnexpectedException: Unexpected application error: SqlException.
System.Data.SqlClient.SqlException: Incorrect syntax near ')'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
....
Thanks
Scheme (how this clarifies the situation somewhat):
Internal DailyTriggerMechanism -----> WCF - Service -----> ASMX-Webservice ----> DB2/SQL
(Origin code above) (Exception being thrown)
Inside the WCF-Service the data recieved is being manipulated to fill specific tables. The AMSX-Webservice may not change in this situation.
I think a normal exception should be able to catch that unhandled error you're listed, but you might try a SOAP-specific, and/or SQL-related exception, in addition to your regular exception.
Like:
try {
//your failing code
}
catch (SOAPException se)
{
//your response }
catch (SQLException sqle)
{
//your response
}
catch (Exception e)
{
//your response
}

InvalidOperationException is ignored in try/catch block

I have the following coding
try
{
var foundCanProperty = properties
.First(x => x.Name == "Can" + method.Name);
var foundOnExecuteMethod = methods
.First(x => x.Name == "On" + method.Name);
var command = new Command(this, foundOnExecuteMethod, foundCanProperty);
TrySetCommand(foundControl as Control, command);
}
catch (InvalidOperationException ex)
{
throw new FatalException("Please check if you have provided all 'On' and 'Can' methods/properties for the view" + View.GetType().FullName, ex);
}
I'd expected that if the methods.First() (in second var statement) throws an InvalidOperationException, I'd be able to catch it. But this seems not be the case (catch block is ignored and the application terminates with the raised exception). If I throw myself an exception of the same type within the try block, it gets caught. Does Linq use multihreading so that the exception is thrown in another thread? Perhaps I make also a stupid error here and just do not see it :(.
Thanks for any help!
I know that this isn't an answer, but rather some additional steps for debugging, but does it change anything if you instead try to catch the general type "Exception" instead of the IOE? That may help to isolate if the method is truly throwing an IOE, or if its failure is generating an IOE somewhere else in the stack. Also - assuming this method isn't in main() - is there a way to wrap the call to it in a try/catch and then inspect the behavior at that point in the call flow?
Apologies, too, in that I know very little about the SilverLight development environment so hopefully the suggestions aren't far fetched.
InvalidOperationException exception occures when The source sequence is empty.
refere to http://msdn.microsoft.com/en-us/library/bb291976.aspx
check weather "properties" or "methods" is not empty.
out of interest, Why you not using FirstOrDefault ?