* @copyright 2021 DIGITAL RETAIL TECHNOLOGIES SL * @license https://opensource.org/licenses/MIT The MIT License * * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ class RetailcrmExceptionMiddleware implements RetailcrmMiddlewareInterface { /** * {@inheritDoc} */ public function __invoke(RetailcrmApiRequest $request, callable $next = null) { try { $response = $next($request); $this->checkResponseType($response); } catch (Exception $e) { $response = $this->getInvalidResponse($request, $e); } catch (Error $e) { $response = $this->getInvalidResponse($request, $e); } return $response; } /** * @throws Exception */ private function checkResponseType($response) { if (!($response instanceof RetailcrmApiResponse)) { throw new Exception( sprintf( 'Expected instance of `%s`, but `%s` given', RetailcrmApiResponse::class, is_object($response) ? get_class($response) : gettype($response) ) ); } } /** * @param RetailcrmApiRequest $request * @param Exception|Error $exception * * @return RetailcrmApiResponse */ private function getInvalidResponse(RetailcrmApiRequest $request, $exception) { $errorMsg = sprintf('Internal error: %s', $exception->getMessage()); RetailcrmLogger::writeCaller($request->getMethod(), $errorMsg); RetailcrmLogger::writeNoCaller($exception->getTraceAsString()); return new RetailcrmApiResponse( 500, json_encode([ 'success' => false, 'errorMsg' => $errorMsg, ]) ); } }