refactor to catch errors and logging