Python尝试在错误变量中包含自定义消息

2024-09-30 20:24:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个简单的尝试,除了,它是工作。但是我想在错误消息的开头添加一些自定义字符串。如果我只是在打印中添加它,它的给定错误

import sys

try:
    with open('./datatype-mapping/file.json') as rs_mapping:
         data_mapping = json.load(rs_mapping)
except Exception as error:
        print('CUSTOM ERROR: '+error)
        sys.exit(1)

我的错误是

Traceback (most recent call last):
  File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 22, in get_datatype_mapping
    with open('./datatype-mapping/file.json') as rs_mapping:
FileNotFoundError: [Errno 2] No such file or directory: './datatype-mapping/file.json'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 102, in <module>
    main()
  File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 99, in main
    target_mapping()
  File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 39, in target_mapping
    data_mapping = get_datatype_mapping()
  File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 26, in get_datatype_mapping
    print('ERROR: '+error)
TypeError: can only concatenate str (not "FileNotFoundError") to str

但是如果我只使用print(error),这是有效的


Tags: inpyjson错误linecodeerrorusers