如何处理错误和消息而不引发异常? (Python式的方式)

问题描述 投票:0回答:1

我有一个程序,里面有很多功能。所有这些函数都调用另一个函数。该函数有 try catch 块来处理错误。我必须在不引发错误的情况下处理这个错误,因为我正在尝试执行 api 应用程序,我失去了处理错误的控制。

所以我写了以下代码块,我怎样才能以Pythonic方式解决这个问题?

def second_funct(param1):
   _return = True
   _error_message = ""
    try:
       print("second_funct")
       #some processing
       print(1/0)
    except Exception as e:
       _return = False
       _error_message = e
    return _return, _error_message

def third_funct(param2):
    _return = True
    _error_message = ""
    try:
        print("third_funct")
        #some processing
    except Exception as e:
        _return = False
        _error_message = e
    return _return, _error_message

def main():
    _return = True
    _error_message = ""
    _param1 = 0
    _param2 = 0
    try:
        print("main_funct")
        #some processing
        _return, _error_message = second_funct(_param1)
        if(_return):
            print("go third_funct")
            _return, _error_message = third_funct(_param2)
            if(_return):
                #some process
                print("ok")
            else:
                print(_error_message)
        else:
            print(_error_message)
    except Exception as e:
        print(e)

main()

此代码的结果;

main_funct
second_funct
division by zero
python error-handling try-catch
1个回答
0
投票

这里是一个你可以做什么的例子,当使用装饰器时,这将使用像 golang 中那样的错误处理,因为你应该始终处理错误。

from functools import wraps

def catch_errors(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
            return result, None
        except Exception as e:
            return None, str(e)
    return wrapper

@catch_errors
def second_funct(param1):
    print("second_funct")
    print(1/0)  # This will cause a division by zero error, demonstrating error handling.

@catch_errors
def third_funct(param2):
    print("third_funct")

def main():
    print("main_funct")
    _param1 = 0
    _param2 = 0
    
    result, err = second_funct(_param1)
    if err:
        print(err)
        return

    print("go third_funct")
    result, err = third_funct(_param2)
    if err:
        print(err)
        return

    print("ok")

main()
© www.soinside.com 2019 - 2024. All rights reserved.