/** * 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); }
/** * Here you can add 'exception -> HTTP code' mapping or custom exception renders. */ private function registerCustomExceptions() { $this->renderContainer->registerHttpCodeMapping([MassAssignmentException::class => Response::HTTP_FORBIDDEN, ExpiredException::class => Response::HTTP_UNAUTHORIZED, SignatureInvalidException::class => Response::HTTP_UNAUTHORIZED, UnexpectedValueException::class => Response::HTTP_BAD_REQUEST]); // // That's an example of how to create custom response with JSON API Error. // $custom404render = $this->getCustom404Render(); // Another example how Eloquent ValidationException could be used. // You can use validation as simple as this // // /** @var \Illuminate\Validation\Validator $validator */ // if ($validator->fails()) { // throw new ValidationException($validator); // } // // and it will return JSON-API error(s) from your API service $customValidationRender = $this->getCustomValidationRender(); // This render is interesting because it takes HTTP Headers from exception and // adds them to HTTP Response (via render parameter $headers) $customTooManyRequestsRender = $this->getCustomTooManyRequestsRender(); $this->renderContainer->registerRender(ModelNotFoundException::class, $custom404render); $this->renderContainer->registerRender(ValidationException::class, $customValidationRender); $this->renderContainer->registerRender(TooManyRequestsHttpException::class, $customTooManyRequestsRender); }