aboutsummaryrefslogtreecommitdiffstats
path: root/pysite/views/api/error_view.py
blob: 30e133f9004d0802106783c1796c2937f47a5bc4 (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
38
39
40
41
# coding=utf-8
from flask import jsonify
from werkzeug.exceptions import HTTPException

from pysite.base_route import ErrorView


class APIErrorView(ErrorView):
    name = "api.error_all"
    error_code = range(400, 600)
    register_on_app = False

    def __init__(self):

        # Direct errors for all methods at self.return_error
        methods = [
            'get', 'post', 'put',
            'delete', 'patch', 'connect',
            'options', 'trace'
        ]

        for method in methods:
            setattr(self, method, self.return_error)

    def return_error(self, error: HTTPException):
        """
        Return a basic JSON object representing the HTTP error,
        as well as propagating its status code
        """

        message = str(error)
        code = 500

        if isinstance(error, HTTPException):
            message = error.description
            code = error.code

        return jsonify({
            "error_code": -1,
            "error_message": message
        }), code