Update error handling; update selector; change delete response code to 200
[pti/o2.git] / o2common / views / route_exception.py
1 # Copyright (C) 2021-2022 Wind River Systems, Inc.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14 from flask import request
15 from flask_restx._http import HTTPStatus
16 from werkzeug.exceptions import (
17     BadRequest,
18     MethodNotAllowed,
19     NotFound,
20     InternalServerError,
21 )
22
23
24 from o2common.helper import o2logging
25 logger = o2logging.get_logger(__name__)
26
27
28 class BadRequestException(BadRequest):
29     def __init__(self, desc=None, resp=None):
30         super().__init__(description=desc, response=resp)
31
32
33 class NotFoundException(NotFound):
34     def __init__(self, desc=None, resp=None):
35         super().__init__(description=desc, response=resp)
36
37
38 class ProblemDetails():
39     def __init__(self, code: int, detail: str,
40                  title=None, instance=None
41                  ) -> None:
42         self.status = code
43         self.detail = detail
44         self.type = request.path
45         self.title = title if title is not None else self.getTitle(code)
46         self.instance = instance if instance is not None else []
47
48     def getTitle(self, code):
49         return HTTPStatus(code).phrase
50
51     def serialize(self):
52         details = {}
53         for key in dir(self):
54             if key == 'ns' or key.startswith('__') or \
55                     callable(getattr(self, key)):
56                 continue
57             else:
58                 details[key] = getattr(self, key)
59         return details
60
61
62 def configure_exception(app):
63
64     @app.errorhandler(BadRequestException)
65     def handle_badrequest_exception(error):
66         '''Return a custom message and 400 status code'''
67         type(error)
68         problem = ProblemDetails(400, str(error))
69         return problem.serialize(), 400
70
71     @app.errorhandler(NotFoundException)
72     def handle_notfound_exception(error):
73         '''Return a custom message and 404 status code'''
74         problem = ProblemDetails(404, str(error))
75         return problem.serialize(), 404
76
77     @app.errorhandler(MethodNotAllowed)
78     def handle_methodnotallowed_exception(error):
79         '''Return a custom message and 405 status code'''
80         problem = ProblemDetails(405, "Method not allowed")
81         return problem.serialize(), 405
82
83     @app.errorhandler(InternalServerError)
84     def handle_internalservererror_exception(error):
85         '''Return a custom message and 500 status code'''
86         problem = ProblemDetails(500, "Internal Server Error")
87         return problem.serialize(), 500