-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathExceptionHandler.php
More file actions
112 lines (99 loc) · 2.82 KB
/
ExceptionHandler.php
File metadata and controls
112 lines (99 loc) · 2.82 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace Foolz\FoolFrame\Model;
use Psr\Log\LoggerInterface;
class ExceptionHandler extends \Symfony\Component\Debug\ExceptionHandler
{
/**
* @var LoggerInterface
*/
protected $logger = null;
/**
* @var LoggerInterface
*/
protected $logger_trace = null;
/**
* Classic logger
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Logger that will print also stack trace
*
* @param LoggerInterface $logger
*/
public function setLoggerTrace(LoggerInterface $logger)
{
$this->logger_trace = $logger;
}
/**
* Sends a response for the given Exception.
*
* If you have the Symfony HttpFoundation component installed,
* this method will use it to create and send the response. If not,
* it will fallback to plain PHP functions.
*
* @param \Exception $exception An \Exception instance
*
* @see sendPhpResponse
* @see createResponse
*/
public function handle(\Exception $exception)
{
if ($this->logger !== null) {
$this->logger->error($exception->getMessage());
}
if ($this->logger_trace !== null) {
$string = $exception->getMessage()."\r\n";
foreach ($exception->getTrace() as $trace) {
$string .= ' ';
if (isset($trace['file'])) {
$string .= 'at '.$trace['file'].'('.$trace['line'].') ';
}
if (isset($trace['class'])) {
$string .= 'in '. $trace['class'].$trace['type'];
}
if (isset($trace['function'])) {
$string .= $trace['function'].'('.$this->stringify($trace['args']).')';
}
$string .= "\r\n";
}
$this->logger_trace->error($string);
}
if (class_exists('Symfony\Component\HttpFoundation\Response')) {
$this->createResponse($exception)->send();
} else {
$this->sendPhpResponse($exception);
}
}
/**
* Creates an acceptable representation of $trace['args']
*
* @param $array
* @param int $depth
*
* @return string
*/
public function stringify($array, $depth = 0)
{
if ($depth > 2) {
return '[...]';
}
$result = [];
foreach ($array as $a) {
if (is_array($a)) {
$result[] = '['.$this->stringify($a, $depth + 1).']';
continue;
}
if (is_object($a)) {
$result[] = get_class($a);
continue;
}
$result[] = $a;
}
return implode(', ', $result);
}
}