aboutsummaryrefslogtreecommitdiff
path: root/web/apache/service.txx
blob: 38fa8adabe8e56464ced6897e449f12acb93a15f (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
// file      : web/apache/service.txx -*- C++ -*-
// copyright : Copyright (c) 2014-2015 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <httpd/http_log.h>

#include <exception>

namespace web
{
  namespace apache
  {
    template <typename M>
    int service::
    handle(request& r, log& l) noexcept
    {
      static const std::string func_name (
        "web::apache::service<" + name_ + ">::handle");

      try
      {
        M m (static_cast<const M&> (exemplar_));
        static_cast<module&> (m).handle (r, r, l);
        return r.flush ();
      }
      catch (const invalid_request& e)
      {
        if (!e.content.empty () && !r.get_write_state ())
        {
          try
          {
            r.content (e.status, e.type) << e.content;
            return r.flush ();
          }
          catch (const std::exception& e)
          {
            l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());
          }
        }

        return e.status;
      }
      catch (const std::exception& e)
      {
        l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());

        if (*e.what () && !r.get_write_state ())
        {
          try
          {
            r.content (HTTP_INTERNAL_SERVER_ERROR, "text/plain;charset=utf-8")
              << e.what ();

            return r.flush ();
          }
          catch (const std::exception& e)
          {
            l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());
          }
        }
      }
      catch (...)
      {
        l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, "unknown error");

        if (!r.get_write_state ())
        {
          try
          {
            r.content (HTTP_INTERNAL_SERVER_ERROR, "text/plain;charset=utf-8")
              << "unknown error";

            return r.flush ();
          }
          catch (const std::exception& e)
          {
            l.write (nullptr, 0, func_name.c_str (), APLOG_ERR, e.what ());
          }
        }
      }

      return HTTP_INTERNAL_SERVER_ERROR;
    }
  }
}