Last active
November 24, 2019 13:55
-
-
Save wfurphy/578633129894fc930ac227a7c5af378e to your computer and use it in GitHub Desktop.
Exception Reporting Trait for Laravel < 5.4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Illuminate\Support\Arr; | |
use Illuminate\Support\Facades\Log; | |
use Illuminate\Contracts\Support\Arrayable; | |
/** | |
* Trait ReportsExceptions | |
* | |
* @package App\Traits | |
* @usage Add `App\Traits\ReportsExceptions` to your class | |
* Then `static::report($exception[,$payload])` anywhere. | |
*/ | |
trait ReportsExceptions | |
{ | |
/** | |
* Report an exception to the log. | |
* | |
* @param \Exception $exception | |
* @param mixed $payload | |
*/ | |
protected static function report(\Exception $exception, $payload = null) | |
{ | |
Log::error($exception->getMessage(), static::makeExceptionArray($exception, $payload)); | |
} | |
/** | |
* Make an Array for reporting the Exception and payload. | |
* | |
* @param \Exception $exception | |
* @param mixed $payload | |
* | |
* @return array | |
*/ | |
protected static function makeExceptionArray(\Exception $exception, $payload = null) | |
{ | |
$array = [ | |
'error' => [ | |
'message' => $exception->getMessage(), | |
'status' => $exception->getStatusCode() ?? 500, | |
'code' => $exception->getCode(), | |
'statusText' => $exception->getMessage(), | |
] | |
]; | |
// Only add debug info if app is in debug mode. | |
if(config('app.debug')) { | |
$payload['error']['debug'] = [ | |
'exception' => get_class($exception), | |
'file' => $exception->getFile(), | |
'line' => $exception->getLine(), | |
'trace' => collect($exception->getTrace())->map(static function ($trace) { | |
return Arr::except($trace, ['args']); | |
})->all() | |
]; | |
} | |
// Add and format payload if it is included | |
switch($payload) { | |
case null: | |
break; | |
case $payload instanceof Arrayable: | |
$array['payload'] = $payload->toArray(); | |
break; | |
case is_array($payload): | |
case is_object($payload): | |
$array['payload'] = (array) $payload; | |
break; | |
default: | |
$array['payload'] = $payload; | |
} | |
return $array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment