2013-02-24 21 views
0

我需要捕获与Django的文件存储API相关的所有异常,可以用于读取或写入等。这里的问题是没有在该API中定义的泛型异常类。例如,当使用FileSystemStorage(默认值)时,抛出的异常是IOError,但是如果我使用的是远程存储,比如S3?我知道我可以添加一些通用的Boto异常,但我想要的是保持此代码的通用性,并与后来选择的任何存储后端解耦。什么是Django中捕获所有异常类regarging文件存储处理?

这是示例代码说明情况:

import contextlib 

class SomeForm(forms.ModelForm): 
    textfield = forms.CharField() 

    class Meta: 
     model = CSSTemplate 

    def __init__(self, *args, **kwargs): 
     super(SomeForm, self).__init__(*args, **kwargs) 

     if not self.is_bound and self.instance and self.instance.file_field: 
      try: 
       with contextlib.closing(self.instance.file_field.file) as file_obj: 
        file_obj.open('r') 
        self['textfield'].field.initial = file_obj.read() 
      except (IOError,): # <-- ??? 
       self.instance.file_field = '' 

我应该检查except子句中有什么异常类?

回答

0
try: 

except OSError: 
    //raise if file is already exist 

except IOError: 
    // is not a directory 

except ValueError: 
    //raise if someone is attempted to access then denied 
+0

这正是我想要避免的,因为这与使用'except:pass'相同。每个异常类都会被困住(因为它们都是“异常”的子类),因此我并没有明确我想要沉默的那种错误。 – 2013-02-24 16:01:01

+0

好的,我会再次搜索你的问题 – catherine 2013-02-24 16:12:10

+0

@Mandx答案更新 – catherine 2013-02-24 16:23:31