Skip to content

Commit

Permalink
refactor: Refactor LogExceptions middleware to handle and log exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
jok3rcito0 committed May 23, 2023
1 parent 05d1ec8 commit 4639894
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions src/Middleware/LogExceptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,33 @@ class LogExceptions implements MiddlewareInterface

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$error_handle = $handler->handle($request);
$body = json_decode($$error_handle->getBody()->getContents(), false);

$error = ($body === null && json_last_error() !== JSON_ERROR_NONE)
? 'Error: Invalid response'
: (empty($body->errors) || !isset($body->errors)) ? $body : $body->errors;
try {
$response = $handler->handle($request);
$body = json_decode($response->getBody()->getContents());

$error = $this->getErrors($body);

if ($response instanceof NonCriticalDomainException) {
Log::error($error, [], self::EXCEPTIONS_CHANNEL);
} else {
Log::critical($error, [], self::EXCEPTIONS_CHANNEL);
}

return $response;
} catch (\Exception $exception) {
Log::critical($exception->getMessage(), [], self::EXCEPTIONS_CHANNEL);
return new Response(500, [], 'Internal Server Error');
}
}

if ($error instanceof NonCriticalDomainException) {
Log::error($error, [], self::EXCEPTIONS_CHANNEL);
} else {
Log::critical($error, [], self::EXCEPTIONS_CHANNEL);
private function getErrors($body)
{
if ($body === null && json_last_error() !== JSON_ERROR_NONE){
$error = 'Error: Invalid response';
}else{
$error = (empty($body->errors) || !isset($body->errors)) ? $body : $body->errors;
}

return $error_handle;
return $error;
}
}

0 comments on commit 4639894

Please sign in to comment.