Add APIException class and refactor code to use it