summaryrefslogtreecommitdiff
path: root/src/exceptions.h
blob: a558adc5d13dc55e855913a31b40fe92f4134925 (plain)
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
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#pragma once

#include <exception>
#include <string>


class BaseException : public std::exception
{
public:
	BaseException(const std::string &s) throw(): m_s(s) {}
	~BaseException() throw() = default;

	virtual const char * what() const throw()
	{
		return m_s.c_str();
	}
protected:
	std::string m_s;
};

class AlreadyExistsException : public BaseException {
public:
	AlreadyExistsException(const std::string &s): BaseException(s) {}
};

class VersionMismatchException : public BaseException {
public:
	VersionMismatchException(const std::string &s): BaseException(s) {}
};

class FileNotGoodException : public BaseException {
public:
	FileNotGoodException(const std::string &s): BaseException(s) {}
};

class DatabaseException : public BaseException {
public:
	DatabaseException(const std::string &s): BaseException(s) {}
};

class SerializationError : public BaseException {
public:
	SerializationError(const std::string &s): BaseException(s) {}
};

class PacketError : public BaseException {
public:
	PacketError(const std::string &s): BaseException(s) {}
};

class SettingNotFoundException : public BaseException {
public:
	SettingNotFoundException(const std::string &s): BaseException(s) {}
};

class ItemNotFoundException : public BaseException {
public:
	ItemNotFoundException(const std::string &s): BaseException(s) {}
};

class ServerError : public BaseException {
public:
	ServerError(const std::string &s): BaseException(s) {}
};

class ClientStateError : public BaseException {
public:
	ClientStateError(const std::string &s): BaseException(s) {}
};

class PrngException : public BaseException {
public:
	PrngException(const std::string &s): BaseException(s) {}
};

class ModError : public BaseException {
public:
	ModError(const std::string &s): BaseException(s) {}
};


/*
	Some "old-style" interrupts:
*/

class InvalidNoiseParamsException : public BaseException {
public:
	InvalidNoiseParamsException():
		BaseException("One or more noise parameters were invalid or require "
			"too much memory")
	{}

	InvalidNoiseParamsException(const std::string &s):
		BaseException(s)
	{}
};

class InvalidPositionException : public BaseException
{
public:
	InvalidPositionException():
		BaseException("Somebody tried to get/set something in a nonexistent position.")
	{}
	InvalidPositionException(const std::string &s):
		BaseException(s)
	{}
};
s="hl str">"Station does not exist") elif isinstance(self._error, str): self._state = False self._error = Exception(self._error) def merge(self, other): """Checks that ``other`` is a :class:`Response` and extends :attr:`departures` by the departures given in ``other`` iff neither response object has a invalid state. """ if isinstance(other, Response): if not other.state: raise ValueError("The response contains errors: " + str(other.error)) elif not self.state: raise ValueError("The response contains errors: " + str(self.error)) else: self.departures.extend(other.departures) else: raise TypeError("The given object is not a response object") @property def to_json(self): """.. deprecated:: 0.0.1 Use :attr:`json` instead. """ return ObjectJSONEncoder(ensure_ascii=False).encode(self.departures) @property def departures(self): """A list of 2-tuple in the form (:class:`str`, :class:`Departure`). The first element in the tuple defines the departing station where the second element holds a list of departure objects. """ if self.state: return self._departures return str(self.error) @property def error(self): """The error that occurred during creation or ``None``""" return self._error @property def json(self): """Uses :class:`~bvggrabber.utils.json.ObjectJSONEncoder` to encode the :attr:`departures` to a JSON format. """ if self.state: return ObjectJSONEncoder(ensure_ascii=False).encode(self.departures) return ObjectJSONEncoder(ensure_ascii=False).encode(str(self.error)) @property def state(self): """``True`` iff the request and parsing was successful, ``False`` otherwise. """ return self._state @total_ordering class Departure(object): def __init__(self, start, end, when, line, since=None, no_add_day=False): """ :param str start: The start station :param str end: The end station :param when: The leaving time of the public transport at the given ``start`` station. Might be an :class:`int` (timestamp), a :class:`datetime.datetime` instance or a :class:`str` accepted by ``dateutil.parse()``. If ``when`` is smaller than ``since`` and the difference between both times is larger than 12 hours (43200sec), the API will add another day unless ``no_add_day`` is ``True``. :param str line: The line of the public transport :param since: Either ``None`` or :class:`datetime.datetime`. Defines the temporal start for searching. ``None`` will internally be resolved as :meth:`datetime.datetime.now`. :param bool no_add_day: If true, there no additional day will be added if ``when`` is smaller than ``since``. Default ``False``. :raises: :exc:`TypeError` if ``when`` is invalid or cannot be parsed. """ if since is None: self.now = datetime.datetime.now() else: self.now = since self.start = start self.end = end self.line = line if isinstance(when, (int, float)): # We assume to get a UNIX / POSIX timestamp self.when = datetime.datetime.fromtimestamp(when) elif isinstance(when, str): # We need to parse a string. But we need to remove trailing # whitespaces and * self.when = parse(re.sub('[\s*]$', '', when)) elif isinstance(when, datetime.datetime): # Everything's fine, we can just take the parameter as is self.when = when else: raise TypeError("when must be a valid datetime, timestamp or " "string!") diff = abs((self.when - self.now).total_seconds()) if not no_add_day and self.when < self.now and diff > 43200: # 43200 are 12 hours in seconds So we accept a offset of 12 hours # that is still counted as "time gone" for the current day. self.when = self.when + datetime.timedelta(days=1) @property def remaining(self): """.. seealso:: bvggrabber.api.compute_remaining""" return int(compute_remaining(self.now, self.when)) def __eq__(self, other): """Two departures are assumed to be equal iff their remaining time and their destination are equal. Right now we do **not** considering the start or line, since that would require some kind of geo location in order to define a *total order*. """ return ((self.remaining, self.end.lower()) == (other.remaining, other.end.lower())) def __lt__(self, other): """A departure is assumed to be less than another iff its remaining time is less than the remaining time of the other departure. Right now we do **not** considering the start, end or line, since that would require some kind of geo location in order to define a *total order*. """ return (self.remaining < other.remaining) def __str__(self): return "Start: %s, End: %s, when: %s, now: %s, line: %s" % ( self.start, self.end, timeformat(self.when), timeformat(self.now), self.line) def __repr__(self): return self.__str__()