我有一個名爲的ExcelFile,他的工作是管理excel文件(讀取,提取數據和堆棧中的不同事物)。管理異常處理
我想實現一個管理錯誤/異常的系統。
例如,ExcelFile爲方法負載(),像一個 「設置」
def load(self):
"""
Setup for excel file
Load workbook, worksheet and others characteristics (data lines, header...)
:return: Setup successfully or not
:rtype: bool
Current usage
:Example:
> excefile = ExcelFile('test.xls')
> excefile.load()
True
> excefile.nb_rows()
4
"""
self.workbook = xlrd.open_workbook(self.url)
self.sheet = self.workbook.sheet_by_index(0)
self.header_row_index = self.get_header_row_index()
if self.header_row_index == None: # If file doesn't have header (or not valid)
return False
self.header_fields = self.sheet.row_values(self.header_row_index)
self.header_fields_col_ids = self.get_col_ids(self.header_fields) # Mapping between header fields and col ids
self.nb_rows = self.count_rows()
self.row_start_data = self.header_row_index + self.HEADER_ROWS
return True
正如你可以看到,我會遇到2個型動物錯誤:
- 的文件不是excel文件(raise xlrd.XLRDError)
- 該文件有一個無效的標題(所以我返回False)
我想實現一個良好的ExcelFile錯誤管理系統,因爲這個類在堆棧中使用了很多。
這是處理我的第一個想法是:
實現一個標準的異常
class ExcelFileException(Exception):
def __init__(self, message, type=None):
self.message = message
self.type = type
def __str__(self):
return "{} : {} ({})".format(self.__class__.__name__, self.message, self.type)
重寫負載方法
def load(self):
"""
Setup for excel file
Load workbook, worksheet and others characteristics (data lines, header...)
:return: Setup successfully or not
:rtype: bool
Current usage
:Example:
> excefile = ExcelFile('test.xls')
> excefile.load()
True
> excefile.nb_rows()
4
"""
try:
self.workbook = xlrd.open_workbook(self.url)
except xlrd.XLRDError as e:
raise ExcelFileException("Unsupported file type", e.__class__.__name__)
self.sheet = self.workbook.sheet_by_index(0)
self.header_row_index = self.get_header_row_index()
if self.header_row_index == None: # If file doesn't have header (or not valid)
raise ExcelFileException("Invalid or empty header")
self.header_fields = self.sheet.row_values(self.header_row_index)
self.header_fields_col_ids = self.get_col_ids(self.header_fields) # Mapping between header fields and col ids
self.nb_rows = self.count_rows()
self.row_start_data = self.header_row_index + self.HEADER_ROWS
return True
而且在呼叫方法,這樣的例子,一個很大的問題是我必須管理一個名爲「報告」的字典,用法語出錯,爲客戶的成功和其他。
...
def foo():
...
file = ExcelFile(location)
try:
file.load()
except ExcelFileException as e:
log.warn(e.__str__())
if e.type == 'XLRDError'
self.report['errors'] = 'Long description of the error, in french (error is about invalid file type)'
else:
self.report['errors'] = 'Long description of the error, in french (error is about invalid header)'
...
您對此有何看法?你有更好的方法嗎? 謝謝
謝謝你,但我有一個條件:1)在報告中的信息必須是在法國和非常明確的(爲客戶的成功和團隊的其他成員) – Alexandre
並不是一個很好的辦法:'raise ExcelFileException(「Error message」,「French description」)' – Alexandre
如果你有錯誤信息存儲在某個地方,你可以使用一個'dict'和一個法語描述錯誤信息,類似'report ['errors']。append(your_dict_with_french_descriptions [message])' – user312016