architex/lib/matrix_server_web/plug/error.ex

32 lines
1.2 KiB
Elixir
Raw Normal View History

2021-06-25 23:14:09 +00:00
defmodule MatrixServerWeb.Plug.Error do
import Plug.Conn
import Phoenix.Controller, only: [json: 2]
@error_map %{
2021-06-25 23:14:09 +00:00
bad_json: {400, "M_BAD_JSON", "Bad request."},
2021-07-13 17:35:02 +00:00
user_in_use: {400, "M_USER_IN_USE", "Username is already taken."},
2021-06-25 23:14:09 +00:00
invalid_username: {400, "M_INVALID_USERNAME", "Invalid username."},
forbidden: {400, "M_FORBIDDEN", "The requested action is forbidden."},
2021-06-26 20:02:18 +00:00
unrecognized: {400, "M_UNRECOGNIZED", "Unrecognized request."},
2021-06-27 15:28:28 +00:00
unknown: {400, "M_UNKNOWN", "An unknown error occurred."},
2021-07-29 20:06:02 +00:00
invalid_room_state:
2021-07-30 13:56:24 +00:00
{400, "M_INVALID_ROOM_STATE", "The request would leave the room in an invalid state."},
2021-06-25 23:14:09 +00:00
unknown_token: {401, "M_UNKNOWN_TOKEN", "Invalid access token."},
2021-07-30 13:56:24 +00:00
missing_token: {401, "M_MISSING_TOKEN", "Access token required."},
not_found: {404, "M_NOT_FOUND", "The requested resource was not found."},
room_alias_exists: {409, "M.UNKNOWN", "The given room alias already exists."}
2021-06-25 23:14:09 +00:00
}
2021-07-30 13:56:24 +00:00
def put_error(conn, {error, msg}), do: put_error(conn, error, msg)
def put_error(conn, error, msg \\ nil) do
{status, errcode, default_msg} = @error_map[error]
2021-07-29 20:06:02 +00:00
data = %{errcode: errcode, error: msg || default_msg}
2021-06-25 23:14:09 +00:00
conn
|> put_status(status)
|> json(data)
|> halt()
end
end