pipe理exception处理

我有一个名为ExcelFile的类,他的工作是pipe理Excel文件(读取,提取数据和堆栈的不同事物)。

我想实现一个pipe理错误/exception的系统。

例如, ExcelFile作为load()方法,就像一个“setup”

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个不同的错误:

  1. 该文件不是一个Excel文件(引发xlrd.XLRDError)
  2. 该文件有一个无效的头(所以我返回False)

我想实现一个良好的ExcelFile错误pipe理系统,因为这个类在堆栈中使用了很多。

这是我处理的第一个想法:

实施一个标准的例外

 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 

而在调用方法中的一个例子,一个大问题是我必须pipe理一个名为“报告”的字典,用法语出错,为了客户的成功等等。

  ... 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)' ... 

你怎么看? 你有更好的方法吗? 谢谢

你可以改变你的exceptionlogging你的dict的错误:

 class ExcelFileException(Exception): def __init__(self, message, report, type=None): report['errors'].append(message) self.message = message self.type = type def __str__(self): return "{} : {} ({})".format(self.__class__.__name__, self.message, self.type) 

当你raise exception

 raise ExcelFileException("Invalid or empty header", report) 

错误将出现在self.dictionnary['errors']

此外,错误可以通过安装缺less一个可选的依赖Xlrd来解决

pip install Xlrd

更多可用的Python包使用Excel时