convert to autocracy
[mdref/mdref] / mdref / ExceptionHandler.php
1 <?php
2
3 namespace mdref;
4
5 use http\Env as HTTP;
6
7 class ExceptionHandler
8 {
9 function __construct() {
10 set_exception_handler($this);
11 set_error_handler($this);
12 }
13
14 function __invoke($e, $msg = null) {
15 if ($e instanceof \Exception) {
16 try {
17 echo static::html($e);
18 } catch (\Exception $ignore) {
19 HTTP::sendStatusCode(500);
20 }
21 } else {
22 throw new \Exception($msg, $e);
23 }
24 return true;
25 }
26
27 static function html(\Exception $e, array $title_tag = ["h1"], array $message_tag = ["p"], array $trace_tag = ["pre", "style='font-size:smaller'"]) {
28 if ($e instanceof \http\Controller\Exception) {
29 $code = $e->getCode() ?: 500;
30 foreach ($e->getHeaders() as $key => $val) {
31 HTTP::sendResponseHeader($key, $val);
32 }
33 } else {
34 $code = 500;
35 }
36 HTTP::setResponseCode($code);
37 $name = HTTP::getResponseStatusForCode($code);
38 $html = sprintf("<%s>%s</%s>\n<%s>%s</%s>\n",
39 implode(" ", $title_tag), $name, $title_tag[0],
40 implode(" ", $message_tag), $e->getMessage(), $message_tag[0]);
41 if ($trace_tag) {
42 $html .= sprintf("<%s>%s</%s>\n",
43 implode(" ", $trace_tag), $e->getTraceAsString(), $trace_tag[0]);
44 }
45 return $html;
46 }
47 }