Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception should I raise for a REST API error?

I am writing a simple API client in Python and I am wondering what exception should I raise if the remote server is not happy.

The API itself is very poorly documented (I don't know all the possible error messages so I can't just define custom classes for all of them), I am letting Requests handle HTTP-level errors which raises HTTPError in those cases, but what should I raise if the server just supplies an error key in the JSON response?

I am currently using Exception but that feels quite broad, I'd like to know whether there's a better alternative.

Regards.

like image 319
André Borie Avatar asked Oct 18 '22 03:10

André Borie


1 Answers

Yes, just raising Exception is likely too broad.

Usually a module should define his own base exception class:

class MyAPIClientError(Exception):
    pass

And then you can subclass that:

class RemoteServerNotHappyError(MyAPIClientError):
    pass

RemoteServerNotHappyError should probably mention something about what the server's json returned that was not expected by your API client class. Add in the relevant error messages as you see fit.

This means users of your library can catch these specific exceptions (which they might know how to handle), without having to catch every exception (they surely don't know how to handle every possible failure mode).

like image 179
wim Avatar answered Oct 21 '22 00:10

wim