1 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # 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, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
17 from functools
import wraps
26 Method_Not_Allowed
= 405
30 Service_Unavailable
= 503
31 Internal_Server_Error
= 500
34 class HttpMappedError(Exception):
35 """Base class for a new hierarchy that translate HTTP error codes
38 This class accepts an extra argument ``http_code`` (integer
39 representing HTTP error codes).
42 def __init__(self
, message
, http_code
=Internal_Server_Error
):
43 Exception.__init
__(self
, message
)
44 self
.http_code
= http_code
47 class ErrorHandler(object):
48 """Defines a default strategy for handling HttpMappedError.
50 This class implements a wrapper (can also be used as decorator), that
51 watches out for different exceptions and log them accordingly.
54 logger(logging.Logger): logger object to be used to report errors
56 def __init__(self
, logger
=None):
57 self
.logger
= logger
or logging
.getLogger('openmano.http')
59 def __call__(self
, function
):
61 def _wraped(*args
, **kwargs
):
63 return function(*args
, **kwargs
)
64 except bottle
.HTTPError
:
66 except HttpMappedError
as ex
:
69 function
.__name
__, ex
.http_code
, exc_info
=True)
70 bottle
.abort(ex
.http_code
, str(ex
))
71 except yaml
.YAMLError
as ex
:
73 "YAML error while trying to serialize/unserialize fields",
75 bottle
.abort(Bad_Request
, type(ex
).__name
__ + ": " + str(ex
))
76 except Exception as ex
:
77 self
.logger
.error("Unexpected exception: ", exc_info
=True)
78 bottle
.abort(Internal_Server_Error
,
79 type(ex
).__name
__ + ": " + str(ex
))