ac1d312c916b6c433ccabf2c163d5eb04631ab60
[vfc/nfvo/lcm.git] / lcm / ns / views / deprecated / common.py
1 # Copyright 2019 ZTE Corporation.
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
15 import traceback
16 import logging
17
18 from rest_framework import status
19 from rest_framework.response import Response
20
21 from lcm.pub.exceptions import BadRequestException
22 from lcm.pub.exceptions import NSLCMException
23
24 logger = logging.getLogger(__name__)
25
26
27 def make_error_resp(status, detail):
28     return Response(
29         data={
30             'status': status,
31             'detail': detail
32         },
33         status=status
34     )
35
36
37 def view_safe_call_with_log(logger):
38     def view_safe_call(func):
39         def wrapper(*args, **kwargs):
40             try:
41                 return func(*args, **kwargs)
42             except BadRequestException as e:
43                 logger.error(e.args[0])
44                 return make_error_resp(
45                     detail=e.args[0],
46                     status=status.HTTP_400_BAD_REQUEST
47                 )
48             except NSLCMException as e:
49                 logger.error(e.args[0])
50                 return make_error_resp(
51                     detail=e.args[0],
52                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
53                 )
54             except Exception as e:
55                 logger.error(e.args[0])
56                 logger.error(traceback.format_exc())
57                 return make_error_resp(
58                     detail='Unexpected exception',
59                     status=status.HTTP_500_INTERNAL_SERVER_ERROR
60                 )
61         return wrapper
62     return view_safe_call