diff --git a/src/Api/ApiServiceProvider.php b/src/Api/ApiServiceProvider.php index 50fbfd12d..d49398eae 100644 --- a/src/Api/ApiServiceProvider.php +++ b/src/Api/ApiServiceProvider.php @@ -25,7 +25,6 @@ use Flarum\Http\RouteCollection; use Flarum\Http\RouteHandlerFactory; use Flarum\Http\UrlGenerator; use Tobscure\JsonApi\ErrorHandler; -use Tobscure\JsonApi\Exception\Handler\FallbackExceptionHandler; use Tobscure\JsonApi\Exception\Handler\InvalidParameterExceptionHandler; use Zend\Stratigility\MiddlewarePipe; @@ -80,7 +79,7 @@ class ApiServiceProvider extends AbstractServiceProvider $handler->registerHandler(new ExceptionHandler\TokenMismatchExceptionHandler); $handler->registerHandler(new ExceptionHandler\ValidationExceptionHandler); $handler->registerHandler(new InvalidParameterExceptionHandler); - $handler->registerHandler(new FallbackExceptionHandler($this->app->inDebugMode())); + $handler->registerHandler(new ExceptionHandler\FallbackExceptionHandler($this->app->inDebugMode(), $this->app->make('log'))); return $handler; }); diff --git a/src/Api/ExceptionHandler/FallbackExceptionHandler.php b/src/Api/ExceptionHandler/FallbackExceptionHandler.php new file mode 100644 index 000000000..f14ce579d --- /dev/null +++ b/src/Api/ExceptionHandler/FallbackExceptionHandler.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Flarum\Api\ExceptionHandler; + +use Exception; +use Psr\Log\LoggerInterface; +use Tobscure\JsonApi\Exception\Handler\ExceptionHandlerInterface; +use Tobscure\JsonApi\Exception\Handler\ResponseBag; + +class FallbackExceptionHandler implements ExceptionHandlerInterface +{ + /** + * @var bool + */ + protected $debug; + + /** + * @var LoggerInterface + */ + protected $logger; + + /** + * @param bool $debug + * @param LoggerInterface $logger + */ + public function __construct($debug, LoggerInterface $logger) + { + $this->debug = $debug; + $this->logger = $logger; + } + + /** + * {@inheritdoc} + */ + public function manages(Exception $e) + { + return true; + } + + /** + * {@inheritdoc} + */ + public function handle(Exception $e) + { + $status = 500; + $error = $this->constructError($e, $status); + + if (! $this->debug) { + $this->logger->error($e); + } + + return new ResponseBag($status, [$error]); + } + + /** + * @param Exception $e + * @param $status + * @return array + */ + private function constructError(Exception $e, $status) + { + $error = ['code' => $status, 'title' => 'Internal server error']; + + if ($this->debug) { + $error['detail'] = (string) $e; + } + + return $error; + } +}