allow for error handling

We (me and sidrees) found your library helpful, but missing out on the error handling, which we desperately need. I asked sidres to propose a change, but he appears to have missed a spot. Here's a more generic approach with a test case. 

For the life of me, I did not find time to find out why on error callback is called twice.