Merge branch 'master' into settings
[diaspy.git] / diaspy / errors.py
1 #!/usr/bin/env python3
2
3
4 class DiaspyError(Exception):
5 """Base exception for all errors
6 raised by diaspy.
7 """
8 pass
9
10
11 class LoginError(DiaspyError):
12 """Exception raised when something
13 bad happens while performing actions
14 related to logging in.
15 """
16 pass
17
18
19 class UserError(DiaspyError):
20 """Exception raised when something related to users goes wrong.
21 """
22 pass
23
24
25 def react(r, message='', accepted=[200, 201, 202, 203, 204, 205, 206], exception=DiaspyError):
26 """This method tries to decides how to react
27 to a response code passed to it. If it's an
28 error code it will raise an exception (it will
29 call `throw()` method.
30
31 If response code is not accepted AND cannot
32 be matched to any exception, generic exception
33 (DiaspyError) is raised (provided that `exception`
34 param was left untouched).
35
36 By default `accepted` param contains all HTTP
37 success codes.
38
39 User can force type of exception to raise by passing
40 `exception` param.
41
42 :param r: response code
43 :type r: int
44 :param message: message for the exception
45 :type message: str
46 :param accepted: list of accepted error codes
47 :type accepted: list
48 :param exception: preferred exception to raise
49 :type exception: valid exception type (default: DiaspyError)
50 """
51 if r in accepted: e = None
52 else: e = DiaspyError
53
54 if e is not None: e = exception
55 throw(e, message=message)
56
57
58 def throw(e, message=''):
59 """This function throws an error with given message.
60 If None is passed as `e` throw() will not raise
61 anything.
62
63 :param e: exception to throw
64 :type e: any valid exception type or None
65 :param message: message for exception
66 :type message: str
67 """
68 if e is None: pass
69 else: raise e(message)