/
errors.py
94 lines (73 loc) · 2.2 KB
/
errors.py
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import json
from flask import make_response, Blueprint
from flask_rest_jsonapi.errors import jsonapi_errors
error_blueprint = Blueprint('errors', __name__)
class ErrorResponse:
"""
Parent ErrorResponse class for handling json-api compliant errors.
Inspired by the JsonApiException class of `flask-rest-jsonapi` itself
"""
title = 'Unknown error'
status = 500
headers = {'Content-Type': 'application/vnd.api+json'}
def __init__(self, source, detail, title=None, status=None):
"""Initialize a jsonapi ErrorResponse Object
:param dict source: the source of the error
:param str detail: the detail of the error
"""
self.source = source
self.detail = detail
if title is not None:
self.title = title
if status is not None:
self.status = status
def respond(self):
"""
:return: a jsonapi compliant response object
"""
dict_ = self.to_dict()
return make_response(json.dumps(jsonapi_errors([dict_])), self.status, self.headers)
def to_dict(self):
"""
:return: Dict from details of the object
"""
return {'status': self.status,
'source': self.source,
'title': self.title,
'detail': self.detail}
class ForbiddenError(ErrorResponse):
"""
Default class for 403 Error
"""
title = 'Access Forbidden'
status = 403
class NotFoundError(ErrorResponse):
"""
Default class for 404 Error
"""
title = 'Not Found'
status = 404
class ServerError(ErrorResponse):
status = 500
title = 'Internal Server Error'
class UnprocessableEntityError(ErrorResponse):
"""
Default class for 422 Error
"""
status = 422
title = 'Unprocessable Entity'
class BadRequestError(ErrorResponse):
"""
Default class for 400 Error
"""
status = 400
title = 'Bad Request'
class RequestLimitError(ErrorResponse):
"""
Default class for 429 Error
"""
status = 429
title = 'Request Limit Exceeded'
@error_blueprint.app_errorhandler(429)
def handle_429(error):
raise RequestLimitError({'source': ''}, error.description).respond()