Commit | Line | Data |
---|---|---|
22422846 MM |
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 | def react(r, message='', accepted=[200, 201, 202, 203, 204, 205, 206], exception=DiaspyError): | |
20 | """This method tries to decides how to react | |
21 | to a response code passed to it. If it's an | |
22 | error code it will raise an exception (it will | |
23 | call `throw()` method. | |
24 | ||
25 | If response code is not accepted AND cannot | |
26 | be matched to any exception, generic exception | |
27 | (DiaspyError) is raised (provided that `exception` | |
28 | param was left untouched). | |
29 | ||
30 | By default `accepted` param contains all HTTP | |
31 | success codes. | |
32 | ||
33 | User can force type of exception to raise by passing | |
34 | `exception` param. | |
35 | ||
36 | :param r: response code | |
37 | :type r: int | |
38 | :param message: message for the exception | |
39 | :type message: str | |
40 | :param accepted: list of accepted error codes | |
41 | :type accepted: list | |
42 | :param exception: preferred exception to raise | |
43 | :type exception: valid exception type (default: DiaspyError) | |
44 | """ | |
45 | if r in accepted: e = None | |
46 | else: e = DiaspyError | |
47 | ||
48 | if e is not None: e = exception | |
49 | throw(e, message=message) | |
50 | ||
51 | ||
52 | def throw(e, message=''): | |
53 | """This function throws an error with given message. | |
54 | If None is passed as `e` throw() will not raise | |
55 | anything. | |
56 | ||
57 | :param e: exception to throw | |
58 | :type e: any valid exception type or None | |
59 | :param message: message for exception | |
60 | :type message: str | |
61 | """ | |
62 | if e is None: pass | |
63 | else: raise e(message) |