litl / rauth

A Python library for OAuth 1.0/a, 2.0, and Ofly.
http://readthedocs.org/docs/rauth/en/latest/
MIT License
1.6k stars 174 forks source link

How do you handle API errors? #120

Open hbrls opened 11 years ago

hbrls commented 11 years ago

The api may return error like this and cause service.get_auth_session not work because it did not have a access_token key.

{ 'error_code': 21332, 'error': 'auth failed', 'request': 'oauth2/access_token.json' }

I'm now handlng it in the decoder like this:

def check_api_error(j):
    if 'error_code' in j:
        raise APIError(j['error_code'], j['error'], j['request'])
    else:
        return j

def decoder(s):
    j = json.loads(s)
    return check_api_error(j)

I think this is not elegant. But it's necessary because api errors are too frequent to ignore. Other than auth failed, the more common reasons might be "you're fetching this api too often" etc.

Will rauth handle this? Or I have to wrap rauth?

maxcountryman commented 11 years ago

It's a little tricky because of course each provider might format their errors differently. For instance, not all providers will return JSON. I'm not opposed to a more dynamic way of handing this though.

hbrls commented 11 years ago

I like the way decoder did it. I'm looking for a similar pattern. And how did you handle http errors? Handled by requestes? There might be a hint.

maxcountryman commented 11 years ago

@shuaishuai sure, feel free to make suggestions. I'm open to pull requests. :)

alertedsnake commented 10 years ago

I was looking into this today - my API returns HTTP error responses properly, but those don't seem to be handled at all! I've hacked my local copy of service.py to throw a requests.exceptions.HTTPError if get_raw_request_token() doesn't get a 200 OK response - this seems to work pretty well for me.

I'm sure other APIs might have error responses you need to parse, but it seems like the very basics of HTTP require handling error responses - at least the 400s and 500s.

I'll continue and then make a pull request if there's interest. Not sure how we'd build unit tests either, without an actual web server..