1 # Copyright (C) 2021-2022 Wind River Systems, Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 (
24 from o2common.helper import o2logging
25 logger = o2logging.get_logger(__name__)
28 class BadRequestException(BadRequest):
29 def __init__(self, desc=None, resp=None):
30 super().__init__(description=desc, response=resp)
33 class NotFoundException(NotFound):
34 def __init__(self, desc=None, resp=None):
35 super().__init__(description=desc, response=resp)
38 class ProblemDetails():
39 def __init__(self, code: int, detail: str,
40 title=None, instance=None
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 []
48 def getTitle(self, code):
49 return HTTPStatus(code).phrase
54 if key == 'ns' or key.startswith('__') or \
55 callable(getattr(self, key)):
58 details[key] = getattr(self, key)
62 def configure_exception(app):
64 @app.errorhandler(BadRequestException)
65 def handle_badrequest_exception(error):
66 '''Return a custom message and 400 status code'''
68 problem = ProblemDetails(400, str(error))
69 return problem.serialize(), 400
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
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
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
89 @app.errorhandler(Exception)
90 def handle_general_exception(error):
91 '''Return a custom message and 500 status code'''
92 problem = ProblemDetails(500, "Internal Server Error")
93 return problem.serialize(), 500