Fix Nullpointer exception and a better handling of errors

Change-Id: I5b46ddd0937fa6c523f2778749c4998cff125ffa