centralize exception handling and make it more flexible