Fix error route response
[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     HTTPException,
22 )
23
24
25 from o2common.helper import o2logging
26 logger = o2logging.get_logger(__name__)
27
28
29 class BadRequestException(BadRequest):
30     def __init__(self, desc=None, resp=None):
31         super().__init__(description=desc, response=resp)
32
33
34 class NotFoundException(NotFound):
35     def __init__(self, desc=None, resp=None):
36         super().__init__(description=desc, response=resp)
37
38
39 class ProblemDetails():
40     def __init__(self, code: int, detail: str,
41                  title=None, instance=None
42                  ) -> None:
43         self.status = code
44         self.detail = detail
45         self.type = request.path
46         self.title = title if title is not None else self.getTitle(code)
47         self.instance = instance if instance is not None else []
48
49     def getTitle(self, code):
50         return HTTPStatus(code).phrase
51
52     def serialize(self):
53         details = {}
54         for key in dir(self):
55             if key == 'ns' or key.startswith('__') or \
56                     callable(getattr(self, key)):
57                 continue
58             else:
59                 details[key] = getattr(self, key)
60         return details
61
62
63 def configure_exception(app):
64
65     @app.errorhandler(HTTPException)
66     def default_error_handler(error):
67         '''Default error handler'''
68         status_code = getattr(error, 'code', 500)
69         problem = ProblemDetails(status_code, str(error))
70         return problem.serialize(), status_code
71
72     @app.errorhandler(NotFound)
73     def handle_notfound(error):
74         '''notfound handler'''
75         problem = ProblemDetails(404, str(error))
76         return problem.serialize(), 404
77
78     @app.errorhandler(BadRequestException)
79     def handle_badrequest_exception(error):
80         '''Return a custom message and 400 status code'''
81         type(error)
82         problem = ProblemDetails(400, str(error))
83         return problem.serialize(), 400
84
85     @app.errorhandler(NotFoundException)
86     def handle_notfound_exception(error):
87         '''Return a custom message and 404 status code'''
88         problem = ProblemDetails(404, str(error))
89         return problem.serialize(), 404
90
91     @app.errorhandler(MethodNotAllowed)
92     def handle_methodnotallowed_exception(error):
93         '''Return a custom message and 405 status code'''
94         problem = ProblemDetails(405, "Method not allowed")
95         return problem.serialize(), 405
96
97     @app.errorhandler(InternalServerError)
98     def handle_internalservererror_exception(error):
99         '''Return a custom message and 500 status code'''
100         problem = ProblemDetails(500, "Internal Server Error")
101         return problem.serialize(), 500
102
103     @app.errorhandler(Exception)
104     def handle_general_exception(error):
105         '''Return a custom message and 500 status code'''
106         problem = ProblemDetails(500, "Internal Server Error")
107         return problem.serialize(), 500