Skip to content

Instantly share code, notes, and snippets.

@inoas
Created September 12, 2019 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inoas/1226835ee066cf54c3bf1f30b1ec028d to your computer and use it in GitHub Desktop.
Save inoas/1226835ee066cf54c3bf1f30b1ec028d to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
namespace App\Error;
use Cake\Error\ErrorHandler;
use Cake\Routing\Exception\MissingControllerException;
use Cake\Http\Exception\GoneException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\UnauthorizedException;
use Cake\Http\Exception\UnavailableForLegalReasonsException;
use Cake\Http\Exception\InvalidCsrfTokenException;
use Cake\Controller\Exception\MissingActionException;
use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Datasource\Exception\InvalidPrimaryKeyException;
use Cake\Log\Log;
use Cake\Routing\Exception\MissingRouteException;
/**
* Defineds logSeparateException() to be used by ErrorHandler::_logException() AND ErrorHandlerMiddleware::logException()
*/
trait ErrorHandlerTrait
{
/**
* Handles exception logging
*
* @param $exceptionOrError Exception or Error instance.
* @return bool
*/
protected function logSeparateException($exceptionOrError) : bool
{
// 401
$unauthorizedExceptionClasses = [
UnauthorizedException::class,
];
// 403
$forbiddenExceptionClasses = [
ForbiddenException::class,
InvalidCsrfTokenException::class,
];
// 404
$notFoundExceptionClasses = [
GoneException::class,
InvalidPrimaryKeyException::class,
MissingActionException::class,
MissingControllerException::class,
MissingRouteException::class,
NotFoundException::class,
RecordNotFoundException::class,
UnavailableForLegalReasonsException::class,
];
$getMessageFn = function($exceptionOrError) {
if ($this instanceof ErrorHandler) {
return $this->_getMessage($exceptionOrError);
}
return $exceptionOrError->getMessage();
};
if (in_array(get_class($exceptionOrError), $notFoundExceptionClasses, true) === true) {
return Log::error($getMessageFn($exceptionOrError), '404');
} else if (in_array(get_class($exceptionOrError), $forbiddenExceptionClasses, true) === true) {
return Log::error($getMessageFn($exceptionOrError), '403');
} else if (in_array(get_class($exceptionOrError), $unauthorizedExceptionClasses, true) === true) {
return Log::error($getMessageFn($exceptionOrError), '401');
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment