Convert a validation exception into a response.

@param  \Illuminate\Http\Request  $request
@param  \Illuminate\Validation\ValidationException  $exception
@return \Illuminate\Http\Response
519963
protected function invalid($request, ValidationException $exception)
    {
        return redirect($exception->redirectTo ?? url()->previous())
                    ->withInput(Arr::except($request->input(), $this->dontFlash))
                    ->withErrors($exception->errors(), $exception->errorBag);
    }
66794
protected function convertValidationExceptionToResponse(ValidationException $e, Request $request)
    {
        if ($e->response) {
            return $e->response;
        }

        $errors = $e->validator->errors()->getMessages();

        if ($request->ajax() || $request->wantsJson()) {
            return Response::json($errors, 422);
        }

        return Redirect::back()->withInput($request->input())->withErrors($errors);
    }
791935
private function generateExceptionResponse($request, Exception $e)
    {
        $formatters = $this->config['formatters'];

        // :: notation will otherwise not work for PHP <= 5.6
        $responseFactoryClass = $this->config['response_factory'];

        // Allow users to have a base formatter for every response.
        $response = $responseFactoryClass::make($e);

        foreach($formatters as $exceptionType => $formatter) {
            if (!($e instanceof $exceptionType)) {
                continue;
            }

            if (
                !class_exists($formatter) ||
                !(new ReflectionClass($formatter))->isSubclassOf(new ReflectionClass(BaseFormatter::class))
            ) {
                throw new InvalidArgumentException(
                    sprintf(
                        "%s is not a valid formatter class.",
                        $formatter
                    )
                );
            }

            $formatterInstance = new $formatter($this->config, $this->debug);
            $formatterInstance->format($response, $e, $this->reportResponses);

            break;
        }

        return $response;
    }
198014
public static function exception(\Exception $exception)
    {
        if (!$exception instanceof RestException) {
            $exception = RestException::createFromException($exception);
        }

        return RestResponse::create(['errors' => $exception->errors()], $exception->getCode());
    }
1253013
public function handleException(\Exception $e): Response
    {
        if ($e instanceof NotFoundException) {
            $this->logger->info('404 Not Found: ' . $this->request->getRequestUri());
            $response = $this->provideNotFoundResponse();
        } elseif ($e instanceof MethodNotAllowedException) {
            $this->logger->notice('Method not allowed.', [
                'request_uri' => $this->request->getRequestUri(),
                'request_method' => $this->request->getRequestMethod(),
            ]);
            $response = $this->provideMethodNotAllowedResponse();
        } elseif ($e instanceof BadRequestException) {
            $this->logger->notice('Bad request.', [
                'request_uri' => $this->request->getRequestUri(),
                'request_method' => $this->request->getRequestMethod(),
            ]);
            $response = $this->provideBadRequestResponse();
        } else {
            $this->logger->error(sprintf('%s in %s:%d', $e->getMessage(), $e->getFile(), $e->getLine()));
            $response = $this->provideGeneralErrorResponse($e);
        }

        return $response;
    }
1061274
protected function errorResponse(Request $request, \Exception $exception): JsonResponse
    {
        if ($exception instanceof EntryNotFoundException || $exception instanceof SectionNotFoundException) {
            $statusCode = JsonResponse::HTTP_NOT_FOUND;
        } else {
            $statusCode = JsonResponse::HTTP_BAD_REQUEST;
        }
        return new JsonResponse([
            'error' => $exception->getMessage()
        ], $statusCode, $this->getDefaultResponseHeaders($request));
    }
1156468
public function jsonResponse(Exception $exception)
    {
        $this->exception = $exception;
        $this->jsonApiResponse = new JsonApiResponse;

        if ($this->exceptionIsTreated()) {
            $this->callExceptionHandler();
        } else {
            $this->setDefaultResponse();
        }

        return response()->json(
            $this->jsonApiResponse->toArray(),
            $this->jsonApiResponse->getStatus()
        );
    }
85546
public function validate() {
		parent::validate();

		if ($this->getEntity() === null) {
			throw new ValidationException("'entity' can't be null", 'entity', $this);
		}
		if ($this->getEntityStates() === null) {
			throw new ValidationException("'entityStates' can't be null", 'entityStates', $this);
		}
		if ($this->getUrl() === null) {
			throw new ValidationException("'url' can't be null", 'url', $this);
		}
	}
36542
protected function error(Request $request, \Exception $exception) {
        return $request->getTarget() . ' threw '
        . get_class($exception) . ': '
        . $exception->getMessage() . "\n"
        . $exception->getTraceAsString();
    }
202337
public function render($request, Exception $e)
    {
        $response = $this->exceptionHandler->render($request, $e);

        if ($this->shouldRenderException($response) === true) {
            $_SERVER = $request->server();
            $response->setContent(
                $this->debuggerManager->exceptionHandler($e)
            );
        }

        return $response;
    }
712051
public function withException(\Exception $exception)
    {
        assert(!is_null($exception), 'Exception must not be null');

        return $this->withDetail('error', $exception->getMessage());
    }
321673
public function validate() {

		if ($this->getCurrency() === null) {
			throw new ValidationException("'currency' can't be null", 'currency', $this);
		}
		if ($this->getProduct() === null) {
			throw new ValidationException("'product' can't be null", 'product', $this);
		}
		if ($this->getSubscription() === null) {
			throw new ValidationException("'subscription' can't be null", 'subscription', $this);
		}
	}
743585
public function handleMicroServiceException(Exception $e)
    {
        // Determine the status code and message to return.
        if ($e instanceof HttpException) {
            return $this->handleHttpException($e);
        } elseif ($e instanceof ModelNotFoundException) {
            return $this->handleModelNotFoundException($e);
        } elseif ($e instanceof ValidationException) {
            return $this->handleValidationException($e);
        } else {
            return $this->handleGenericException($e);
        }
    }
118487
public function start(Request $request, AuthenticationException $exception = null)
    {
        if ($exception) {
            $message = $exception->getMessage();
            if (empty($message) && is_callable([$exception, 'getMessageKey'])) {
                $message = $e->getMessageKey();
            }
        } else {
            $message = 'Full authentication is required to access this resource.';
        }

        $content = [
            'errors' => [
                'code' => 401,
                'message' => $this->translator->trans($message, [], 'errors')
            ]
        ];

        return new JsonResponse($content, JsonResponse::HTTP_UNAUTHORIZED);
    }
574112
protected function handleRequestException(Request $request, RequestException $previousException)
    {
        if (null !== $previousException) {
            $response = $previousException->getResponse();

            if (null == $response || ($response->getStatusCode() >= 500 && $response->getStatusCode() <= 599)) {
                throw new NullResponseException($this->request, $previousException);
            }
        }

        throw $this->createApiException(
            $request,
            $this->createResponse($previousException->getResponse()),
            $previousException
        );
    }
1293492
public function handleAndResponseException(\Exception $ex)
    {

        $response = '';
        switch (true) {
            case $ex instanceof \Illuminate\Database\Eloquent\ModelNotFoundException:
                $response = $this->respondNotFound('Record not found');
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException:
                $response = $this->respondNotFound("Not found");
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException:
                $response = $this->respondForbidden("Access denied");
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\BadRequestHttpException:
                $response = $this->respondBadRequest("Bad request");
                break;
            case $ex instanceof BadMethodCallException:
                $response = $this->respondBadRequest("Bad method Call");
                break;
            case $ex instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException:
                $response = $this->respondForbidden("Method not found");
                break;
            case $ex instanceof \Illuminate\Database\QueryException:
                $response = $this->respondValidationError("Some thing went wrong with your query", [$ex->getMessage()]);
                break;
            case $ex instanceof \Illuminate\Http\Exceptions\HttpResponseException:
                $response = $this->respondInternalError("Something went wrong with our system", [$ex->getMessage()]);
                break;
            case $ex instanceof \Illuminate\Auth\AuthenticationException:
                $response = $this->respondUnauthorized("Unauthorized request");
                break;
            case $ex instanceof \Illuminate\Validation\ValidationException:
                $response = $this->respondValidationError("In valid request", [$ex->getMessage()]);
                break;
            case $ex instanceof NotAcceptableHttpException:
                $response = $this->respondUnauthorized("Unauthorized request");
                break;
            case $ex instanceof \Illuminate\Validation\UnauthorizedException:
                $response = $this->respondUnauthorized("Unauthorized request", [$ex->getMessage()]);
                break;
            case $ex instanceof \Exception:
                $response = $this->respondInternalError("Something went wrong with our system", [$ex->getMessage()]);
                break;
        }
        return $response;
    }
743828
public function handle(Request $request) : ResponseInterface
  {
    // Reset current context to root context
    $this->currentContext = $this->rootContext;
    if (!$result = $this->handleContext($request, $this->rootContext, true)) {
      throw new HttpException(404);
    }

    return $result;
  }