-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogAndThrowExceptionTrait.php
68 lines (64 loc) · 2.84 KB
/
LogAndThrowExceptionTrait.php
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
<?php
declare(strict_types=1);
namespace Oro\Component\Log;
use Monolog\Processor\PsrLogMessageProcessor;
/**
* Provides the following methods to log a message to the logger and throw an exception:
* - **throwErrorException()** logs an error message and throws an exception;
* - **throwCriticalException()** logs a critical message and throws an exception.
*/
trait LogAndThrowExceptionTrait
{
/**
* Logs an error message and throws an exception of the specified type with the provided message text.
* Do not use \sprintf() to add variables to the message, use placeholders instead and put variables
* under named keys in the context as required by Oro logging conventions.
* @see https://doc.oroinc.com/backend/logging/#message
* @see https://github.com/Seldaek/monolog/blob/2.2.0/doc/message-structure.md
*/
protected function throwErrorException(
string $exceptionClassname,
string $message,
array $context = [],
?\Throwable $previous = null,
int $code = 0
): void {
$processedMessage = (new PsrLogMessageProcessor())(['message' => $message, 'context' => $context])['message'];
if (null !== $this->logger) {
$trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
$calledIn = $trace['file'] . ':' . $trace['line'];
$context['called_in'] = $calledIn;
if (null !== $previous) {
$context['exception'] = $previous;
}
$this->logger->error($message, $context);
}
throw new $exceptionClassname($processedMessage, $code, $previous);
}
/**
* Logs a critical message and throws an exception of the specified type with the provided message text.
* Do not use \sprintf() to add variables to the message, use placeholders instead and put variables
* under named keys in the context as required by Oro logging conventions.
* @see https://doc.oroinc.com/backend/logging/#message
* @see https://github.com/Seldaek/monolog/blob/2.2.0/doc/message-structure.md
*/
protected function throwCriticalException(
string $exceptionClassname,
string $message,
array $context = [],
?\Throwable $previous = null,
int $code = 0
): void {
$processedMessage = (new PsrLogMessageProcessor())(['message' => $message, 'context' => $context])['message'];
if (null !== $this->logger) {
$trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
$calledIn = $trace['file'] . ':' . $trace['line'];
$context['called_in'] = $calledIn;
if (null !== $previous) {
$context['exception'] = $previous;
}
$this->logger->critical($message, $context);
}
throw new $exceptionClassname($processedMessage, $code, $previous);
}
}