Add avoiding NPE, catch errors and enhance logging