/** * @return Closure */ private function getCustomTooManyRequestsRender() { $customTooManyRequestsRender = function (Request $request, TooManyRequestsHttpException $exception) { $request ?: null; // avoid 'unused' warning // This render can convert JSON API Error to Response $jsonApiErrorRender = $this->renderContainer->getErrorsRender(Response::HTTP_TOO_MANY_REQUESTS); // Prepare Error object (e.g. take info from the exception) $title = 'Validation fails'; $message = $exception->getMessage(); $headers = $exception->getHeaders(); $error = new Error(null, null, null, null, $title, $message); // Convert error (note it accepts array of errors) to HTTP response return $jsonApiErrorRender([$error], $this->getEncoderOptions(), $this->mergeCorsHeadersTo($headers)); }; return $customTooManyRequestsRender; }
/** * Here you can add 'exception -> HTTP code' mapping or custom exception renders. */ private function registerCustomExceptions() { $this->renderContainer->registerHttpCodeMapping([MassAssignmentException::class => Response::HTTP_FORBIDDEN]); // // That's an example of how to create custom response with JSON API Error. // $custom404render = function () { // This render can convert JSON API Error to Response $jsonApiErrorRender = $this->renderContainer->getErrorsRender(Response::HTTP_NOT_FOUND); // Prepare Error object (e.g. take info from the exception) $title = 'Requested item not found'; $error = new Error(null, null, null, null, $title); // Load JSON formatting options from config $opts = array_get($this->integration->getConfig(), C::JSON . '.' . C::JSON_OPTIONS, C::JSON_OPTIONS_DEFAULT); $encodeOptions = new EncoderOptions($opts); // Convert error (note it accepts array of errors) to HTTP response return $jsonApiErrorRender([$error], $encodeOptions); }; $this->renderContainer->registerRender(ModelNotFoundException::class, $custom404render); }