summary refs log tree commit diff
path: root/synapse/api/errors.py
blob: 8e9dd2aba6761c75259408b988d185ec03d9ff8d (plain) (blame)
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
# -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Contains exceptions and error codes."""

import logging


class Codes(object):
    FORBIDDEN = "M_FORBIDDEN"
    BAD_JSON = "M_BAD_JSON"
    NOT_JSON = "M_NOT_JSON"
    USER_IN_USE = "M_USER_IN_USE"
    ROOM_IN_USE = "M_ROOM_IN_USE"
    BAD_PAGINATION = "M_BAD_PAGINATION"
    UNKNOWN = "M_UNKNOWN"
    NOT_FOUND = "M_NOT_FOUND"
    UNKNOWN_TOKEN = "M_UNKNOWN_TOKEN"
    LIMIT_EXCEEDED = "M_LIMIT_EXCEEDED"
    NEEDS_CAPTCHA = "M_NEEDS_CAPTCHA"


class CodeMessageException(Exception):
    """An exception with integer code and message string attributes."""

    def __init__(self, code, msg):
        logging.error("%s: %s, %s", type(self).__name__, code, msg)
        super(CodeMessageException, self).__init__("%d: %s" % (code, msg))
        self.code = code
        self.msg = msg
        self.response_code_message = None

    def error_dict(self):
        return cs_error(self.msg)


class SynapseError(CodeMessageException):
    """A base error which can be caught for all synapse events."""
    def __init__(self, code, msg, errcode=Codes.UNKNOWN):
        """Constructs a synapse error.

        Args:
            code (int): The integer error code (typically an HTTP response code)
            msg (str): The human-readable error message.
            err (str): The error code e.g 'M_FORBIDDEN'
        """
        super(SynapseError, self).__init__(code, msg)
        self.errcode = errcode

    def error_dict(self):
        return cs_error(
            self.msg,
            self.errcode,
        )

class RoomError(SynapseError):
    """An error raised when a room event fails."""
    pass


class RegistrationError(SynapseError):
    """An error raised when a registration event fails."""
    pass


class AuthError(SynapseError):
    """An error raised when there was a problem authorising an event."""

    def __init__(self, *args, **kwargs):
        if "errcode" not in kwargs:
            kwargs["errcode"] = Codes.FORBIDDEN
        super(AuthError, self).__init__(*args, **kwargs)


class EventStreamError(SynapseError):
    """An error raised when there a problem with the event stream."""
    def __init__(self, *args, **kwargs):
        if "errcode" not in kwargs:
            kwargs["errcode"] = Codes.BAD_PAGINATION
        super(EventStreamError, self).__init__(*args, **kwargs)


class LoginError(SynapseError):
    """An error raised when there was a problem logging in."""
    pass


class StoreError(SynapseError):
    """An error raised when there was a problem storing some data."""
    pass


class LimitExceededError(SynapseError):
    """A client has sent too many requests and is being throttled.
    """
    def __init__(self, code=429, msg="Too Many Requests", retry_after_ms=None,
                 errcode=Codes.LIMIT_EXCEEDED):
        super(LimitExceededError, self).__init__(code, msg, errcode)
        self.retry_after_ms = retry_after_ms
        self.response_code_message = "Too Many Requests"

    def error_dict(self):
        return cs_error(
            self.msg,
            self.errcode,
            retry_after_ms=self.retry_after_ms,
        )


def cs_exception(exception):
    if isinstance(exception, CodeMessageException):
        return exception.error_dict()
    else:
        logging.error("Unknown exception type: %s", type(exception))


def cs_error(msg, code=Codes.UNKNOWN, **kwargs):
    """ Utility method for constructing an error response for client-server
    interactions.

    Args:
        msg (str): The error message.
        code (int): The error code.
        kwargs : Additional keys to add to the response.
    Returns:
        A dict representing the error response JSON.
    """
    err = {"error": msg, "errcode": code}
    for key, value in kwargs.iteritems():
        err[key] = value
    return err