error_hook_app.erl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. %% Feel free to use, reuse and abuse the code in this file.
  2. %% @private
  3. -module(error_hook_app).
  4. -behaviour(application).
  5. %% API.
  6. -export([start/2]).
  7. -export([stop/1]).
  8. %% API.
  9. start(_Type, _Args) ->
  10. Dispatch = cowboy_router:compile([
  11. {'_', []}
  12. ]),
  13. {ok, _} = cowboy:start_http(http, 100, [{port, 8080}], [
  14. {env, [{dispatch, Dispatch}]},
  15. {onresponse, fun error_hook/4}
  16. ]),
  17. error_hook_sup:start_link().
  18. stop(_State) ->
  19. ok.
  20. error_hook(404, Headers, <<>>, Req) ->
  21. Path = cowboy_req:path(Req),
  22. Body = ["404 Not Found: \"", Path,
  23. "\" is not the path you are looking for.\n"],
  24. Headers2 = lists:keyreplace(<<"content-length">>, 1, Headers,
  25. {<<"content-length">>, integer_to_list(iolist_size(Body))}),
  26. cowboy_req:reply(404, Headers2, Body, Req);
  27. error_hook(Code, Headers, <<>>, Req) when is_integer(Code), Code >= 400 ->
  28. Body = ["HTTP Error ", integer_to_list(Code), $\n],
  29. Headers2 = lists:keyreplace(<<"content-length">>, 1, Headers,
  30. {<<"content-length">>, integer_to_list(iolist_size(Body))}),
  31. cowboy_req:reply(Code, Headers2, Body, Req);
  32. error_hook(_Code, _Headers, _Body, Req) ->
  33. Req.