error_catch.py 2.8 KB
Newer Older
F
felixhjh 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
import sys 
import enum 
import os 
import logging 
import traceback
from paddle_serving_server.pipeline import ResponseOp
import threading
import inspect
import traceback
import functools
import re
from .proto import pipeline_service_pb2_grpc, pipeline_service_pb2

_LOGGER = logging.getLogger(__name__) 

class Singleton(object):
    _lock = threading.Lock()
    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._lock:
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return Singleton._instance

    def set_exception_response(self, error_code, error_info):
F
felixhjh 已提交
26
        
F
felixhjh 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
        self.resp = pipeline_service_pb2.Response()
        self.resp.err_no = error_code
        self.resp.err_msg = error_info.replace("\n", " ").replace("\t", " ")[2:]

    def get_exception_response(self):
        if hasattr(self, "resp"):
            return self.resp
        else:
            return None

class CustomExceptionCode(enum.Enum): 
    """
    Add new Exception
    """
    INTERNAL_EXCEPTION = 0
    TYPE_EXCEPTION = 1
    TIMEOUT_EXCEPTION = 2
    CONF_EXCEPTION = 3
    PARAMETER_INVALID = 4

class CustomException(Exception):
F
felixhjh 已提交
48
    def __init__(self, exceptionCode, errorMsg, isSendToUser):
F
felixhjh 已提交
49 50 51
        super().__init__(self)
        self.error_info = "\n\texception_code: {}\n"\
                          "\texception_type: {}\n"\
F
felixhjh 已提交
52 53 54
                          "\terror_msg: {}"\
                          "\tis_send_to_user: {}".format(exceptionCode.value,
                          CustomExceptionCode(exceptionCode).name, errorMsg, isSendToUser)
F
felixhjh 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    
    def __str__(self):
        return self.error_info

class ErrorCatch():
    def __call__(self, func):
        if inspect.isfunction(func) or inspect.ismethod(func):
            @functools.wraps(func)
            def wrapper(*args, **kw):
                try:
                    func(*args, **kw)
                except CustomException  as e:
                    _LOGGER.error("{}\tFunctionName: {}{}".format(traceback.format_exc(), func.__name__, args))
                    split_list = re.split("\n|\t|:", str(e))
                    error_code = int(split_list[3])
F
felixhjh 已提交
70 71 72 73 74 75 76
                    error_info = "{}\n\tClassName: {} FunctionName: {}".format(str(e), func.__class__ ,func.__name__)
                    is_send_to_user = split_list[-1]
                    if is_send_to_user == True:
                        self.record_error_info(error_code, error_info)
                    else:
                        raise("server error occur")

F
felixhjh 已提交
77 78 79 80 81 82 83
            return wrapper
    
    def record_error_info(self, error_code, error_info):
        ExceptionSingleton.set_exception_response(error_code, error_info)

ErrorCatch = ErrorCatch()
ExceptionSingleton = Singleton()