aboutsummaryrefslogtreecommitdiff
path: root/apps/dreki/src/dreki_error.erl
blob: 1ca2125e98e7b1c9d341c2d5d4f8490db6200c77 (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
-module(dreki_error).
-compile({no_auto_import,[error/3]}).
-export([errors/0, error/1, error/2, error/3, error/4, error/5]).
-export([as_map/1]).

-record(?MODULE, {
  code :: atom(),
  status = 500,
  title :: binary(),
  detail = undefined :: undefined | binary(),
  source = [] :: [source]
}).

-type t() :: #?MODULE{}.

-type source() :: {urn, dreki_urn:urn()} | {pointer, JSONPointer :: binary()} | {parameter, binary()} | {binary(), binary()}.

errors() -> [
    #?MODULE{code = exists, status = 409, title = <<"Already exists">>},
    #?MODULE{code = not_found, status = 404, title = <<"Not Found">>},
    #?MODULE{code = error, status = 500, title = <<"Error">>},
    #?MODULE{code = store_start_failed, status = 500, title = <<"Store start failed">>}
].

error(Code) ->
    error(Code, undefined, []).

error(Code, Source) when is_list(Source) ->
    error(Code, undefined, Source);
error(Code, Detail) when is_binary(Detail) ->
    error(Code, Detail, []).

error(Code, Detail, Source) when is_binary(Detail) or is_atom(Detail) and is_list(Source) ->
    {error, case lists:keyfind(Code, 2, errors()) of
        Error = #?MODULE{} -> Error#?MODULE{detail = Detail, source = Source};
        _ -> #?MODULE{code = error, status = 500, title = <<"Error">>, detail = Detail, source = Source}
    end};

error(Code, Status, Title) when is_atom(Code) and is_integer(Status) and is_binary(Title) ->
    {error, #?MODULE{code = Code, status = Status, title = Title}}.

error(Code, Status, Title, Detail) when is_integer(Status) and is_binary(Title) and is_binary(Detail) ->
    {error, #?MODULE{code = Code, status = Status, title = Title, detail = Detail}};
error(Code, Status, Title, Source) when is_integer(Status) and is_binary(Title) and is_list(Source) ->
    {error, #?MODULE{code = Code, status = Status, title = Title, source = Source}}.

error(Code, Status, Title, Detail, Source) when is_integer(Status) and is_binary(Title) and is_list(Source) and is_binary(Detail) ->
    {error, #?MODULE{code = Code, status = Status, title = Title, detail = Detail, source = Source}}.

as_map(#?MODULE{code = Code, status = Status, title = Title, detail = Detail, source = Source}) ->
  #{code => Code, status => Status, title => Title, detail => Detail, source => Source}.