Adding cover to tox.ini default envs
[osm/RO.git] / RO / osm_ro / http_tools / errors.py
1 # -*- coding: utf-8 -*-
2 ##
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
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, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14 ##
15
16 import logging
17 from functools import wraps
18
19 import bottle
20 import yaml
21
22 Bad_Request = 400
23 Unauthorized = 401
24 Not_Found = 404
25 Forbidden = 403
26 Method_Not_Allowed = 405
27 Not_Acceptable = 406
28 Request_Timeout = 408
29 Conflict = 409
30 Service_Unavailable = 503
31 Internal_Server_Error = 500
32
33
34 class HttpMappedError(Exception):
35 """Base class for a new hierarchy that translate HTTP error codes
36 to python exceptions
37
38 This class accepts an extra argument ``http_code`` (integer
39 representing HTTP error codes).
40 """
41
42 def __init__(self, message, http_code=Internal_Server_Error):
43 Exception.__init__(self, message)
44 self.http_code = http_code
45
46
47 class ErrorHandler(object):
48 """Defines a default strategy for handling HttpMappedError.
49
50 This class implements a wrapper (can also be used as decorator), that
51 watches out for different exceptions and log them accordingly.
52
53 Arguments:
54 logger(logging.Logger): logger object to be used to report errors
55 """
56 def __init__(self, logger=None):
57 self.logger = logger or logging.getLogger('openmano.http')
58
59 def __call__(self, function):
60 @wraps(function)
61 def _wraped(*args, **kwargs):
62 try:
63 return function(*args, **kwargs)
64 except bottle.HTTPError:
65 raise
66 except HttpMappedError as ex:
67 self.logger.error(
68 "%s error %s",
69 function.__name__, ex.http_code, exc_info=True)
70 bottle.abort(ex.http_code, str(ex))
71 except yaml.YAMLError as ex:
72 self.logger.error(
73 "YAML error while trying to serialize/unserialize fields",
74 exc_info=True)
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))
80
81 return _wraped