~sschwarzer/ftputil

ref: 85db55cce826041a8ec7187d9cb9d1265e2fa2ea ftputil/ftputil/error.py -rw-r--r-- 4.8 KiB
85db55ccStefan Schwarzer Make error handling more robust. 8 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# Copyright (C) 2003-2014, Stefan Schwarzer <sschwarzer@sschwarzer.net>
# See the file LICENSE for licensing terms.

"""
ftputil.error - exception classes and wrappers
"""

# pylint: disable=too-many-ancestors

from __future__ import unicode_literals

import ftplib

import ftputil.version


# You _can_ import these with `from ftputil.error import *`, - but
# it's _not_ recommended.
__all__ = [
 "InternalError",
  "RootDirError",
  "InaccessibleLoginDirError",
  "TimeShiftError",
  "ParserError",
  "KeepAliveError",
  "FTPOSError",
  "TemporaryError",
  "PermanentError",
  "CommandNotImplementedError",
  "SyncError",
  "FTPIOError",
]


class FTPError(Exception):
    """General ftputil error class."""

    # In Python 2, we can't use a keyword argument after `*args`, so
    # `pop` from `**kwargs`.
    def __init__(self, *args, **kwargs):
        super(FTPError, self).__init__(*args)
        if "original_exception" in kwargs:
            self.strerror = ftputil.tool.as_unicode(
                              kwargs.pop("original_exception"))
        elif args:
            # If there was no `original_exception` argument, assume
            # the first argument is a string. It may be a byte string
            # though.
            self.strerror = ftputil.tool.as_unicode(args[0])
        else:
            self.strerror = ""
        try:
            self.errno = int(self.strerror[:3])
        except (TypeError, IndexError, ValueError):
            # TODO: List where all these exceptions may come from.
            self.errno = None
        self.file_name = None

    def __str__(self):
        return "{0}\nDebugging info: {1}".format(self.strerror,
                                                 ftputil.version.version_info)


# Internal errors are those that have more to do with the inner
# workings of ftputil than with errors on the server side.
class InternalError(FTPError):
    """Internal error."""
    pass

class RootDirError(InternalError):
    """Raised for generic stat calls on the remote root directory."""
    pass

class InaccessibleLoginDirError(InternalError):
    """May be raised if the login directory isn't accessible."""
    pass

class TimeShiftError(InternalError):
    """Raised for invalid time shift values."""
    pass

class ParserError(InternalError):
    """Raised if a line of a remote directory can't be parsed."""
    pass

class CacheMissError(InternalError):
    """Raised if a path isn't found in the cache."""
    pass

# Currently not used
class KeepAliveError(InternalError):
    """Raised if the keep-alive feature failed."""
    pass

class FTPOSError(FTPError, OSError):
    """Generic FTP error related to `OSError`."""
    pass

class TemporaryError(FTPOSError):
    """Raised for temporary FTP errors (4xx)."""
    pass

class PermanentError(FTPOSError):
    """Raised for permanent FTP errors (5xx)."""
    pass

class CommandNotImplementedError(PermanentError):
    """Raised if the server doesn't implement a certain feature (502)."""
    pass

# Currently not used
class SyncError(PermanentError):
    """Raised for problems specific to syncing directories."""
    pass


class FtplibErrorToFTPOSError(object):
    """
    Context manager to convert `ftplib` exceptions to exceptions
    derived from `FTPOSError`.
    """

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            # No exception
            return
        if isinstance(exc_value, ftplib.error_temp):
            raise TemporaryError(*exc_value.args, original_exception=exc_value)
        elif isinstance(exc_value, ftplib.error_perm):
            # If `exc_value.args[0]` is present, assume it's a byte or
            # unicode string.
            if (
              exc_value.args and
              ftputil.tool.as_unicode(exc_value.args[0]).startswith("502")
            ):
                raise CommandNotImplementedError(*exc_value.args)
            else:
                raise PermanentError(*exc_value.args,
                                     original_exception=exc_value)
        elif isinstance(exc_value, ftplib.all_errors):
            raise FTPOSError(*exc_value.args, original_exception=exc_value)
        else:
            raise

ftplib_error_to_ftp_os_error = FtplibErrorToFTPOSError()


class FTPIOError(FTPError, IOError):
    """Generic FTP error related to `IOError`."""
    pass


class FtplibErrorToFTPIOError(object):
    """
    Context manager to convert `ftplib` exceptions to `FTPIOError`
    exceptions.
    """

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            # No exception
            return
        if isinstance(exc_value, ftplib.all_errors):
            raise FTPIOError(*exc_value.args, original_exception=exc_value)
        else:
            raise

ftplib_error_to_ftp_io_error = FtplibErrorToFTPIOError()