从异常类型对象获取类名

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

考虑这个方法,我需要打印

ValueError
,而不是打印
type

我做错了什么?

import sys
import traceback

def test():
    try:
        raise ValueError('Test')
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print(exc_type.__class__.__name__)


test()
python exception
1个回答
0
投票

这是我解决问题的方法:

except Exception as error:
    exc_info = sys.exc_info()

    sExceptionInfo = ''.join(traceback.format_exception(*exc_info))

    exc_type, exc_value, exc_context = sys.exc_info()

    rHttpResponse = JsonResponse( 
        {
            "status": "error",
            "type": exc_type.__name__,
            "description": str(exc_value),
            "details": sExceptionInfo 
        }
    )

return rHttpResponse

我不得不调用 exc_info() 两次,因为两种类型的返回值之间 exc_info 的格式不同。

目标是将任何异常序列化为实际异常:

  • “type”是实际的异常类名称(例如 AttributeError)
  • “描述”是简短的细节(例如“str”属性没有属性“_meta”)
  • “详细信息”是代码、文件、行号、调用堆栈的回溯列表。

最终结果是 UI 可以确定显示多少内容,以便为用户提供一些智能错误消息以捕获并发送给帮助台。

© www.soinside.com 2019 - 2024. All rights reserved.