Changed and fixed error handling
working version
Finally error handling should be correct.