3

这是我想捕捉的错误:

 Traceback:
    File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
      111.                         response = callback(request, *callback_args, **callback_kwargs)
    File "/opt/django/fileupload/views.py" in upload_file
      56.         folder_info = url.split(':')[1] #Extracts folder info to use in the header

    Exception Type: IndexError at /upload_file/
    Exception Value: list index out of range

尝试使用:

except (socket.error, paramiko.AuthenticationException, IndexError):
            return render_to_response('reform.html', context_instance=RequestContext(request))

但它不起作用。

我能够捕获socket.errorandparamiko.Authentication异常,但不能捕获IndexError. 我试图在 Django 中捕获异常。谢谢。

编辑:整个 try 和 except 块:

try:        
    source = str(username) + "@" + url #Source to list all the files
    add_key = str(username) + "@" + test_url
    add_known_hosts(password, add_key) #Add to the known hosts
    test_ssh(test_url, username, password) #Test Host_name, username and password
    destination = '/home/sachet/files'    
    command = subprocess.Popen(['sshpass', '-p', password, 'rsync', '--recursive', source],
                   stdout=subprocess.PIPE).communicate()[0] #sshpass needs to be installed into the server
    lines = (x.strip() for x in command.split('\n'))
    remote = [x.split(None, 4)[-1] for x in lines if x] #Removes permission from the file listing
    base_name = [os.path.basename(ok) for ok in remote]
    result = subprocess.Popen(['ls', destination], stdout=subprocess.PIPE).communicate()[0].splitlines()

    return render_to_response('thanks.html', {'res1': remote, 'res': result, 'folder': folder_info}, context_instance=RequestContext(request))
except (socket.error, paramiko.AuthenticationException, IndexError):
    return render_to_response('reform.html', context_instance=RequestContext(request)) 
4

1 回答 1

1

IndexError 不会在您发布的 try/except 块中引发。IndexError 在 folder_info 分配到的行(views.py 中的第 56 行)引发。您需要将该行代码移动到您的 try/except 块中以捕获该错误。

File "/opt/django/fileupload/views.py" in upload_file
    56.         folder_info = url.split(':')[1]  <-- This line

或者,更好的是,在“folder = ...”行周围放置一个单独的try/except,仅针对IndexError,以使您的代码意图更清晰。

于 2012-12-19T08:51:16.960 回答