error handlin, refactor