aboutsummaryrefslogtreecommitdiffstats
path: root/github3/errors.py
blob: 09e616b07a46531286d989141480c9d870a959de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# author: David Medina

import json
import github3.exceptions as exceptions

class GithubError(object):
    """ Handler for API errors """

    def __init__(self, response):
        self._parser = json
        self.status_code = response.status_code
        try:
            self.debug = self._parser.loads(response.content)
        except ValueError:
            self.debug = {'message': response.content}

    def error_400(self):
        return exceptions.BadRequest("400 - %s" % self.debug.get('message'))

    def error_404(self):
        return exceptions.NotFound("404 - %s" % self.debug.get('message'))

    def error_422(self):
        errors = self.debug.get('errors')
        if errors:
            errors = ['{resource}: {code} => {field}'.format(**error)
                      for error in errors]
        return exceptions.UnprocessableEntity(
            '422 - %s %s' % (self.debug.get('message'), errors))

    def process(self):
        raise_error = getattr(self, 'error_%s' % self.status_code, False)
        if raise_error:
            raise raise_error()