refactor code to handle error exception