如何防止JSON异常

问题描述 投票:1回答:1

Laravel(5.5)显然以json格式而不是whoop页面返回异常。我在哪里可以禁用这种烦人的行为并收到whoops或默认的php异常格式?

json laravel exception
1个回答
1
投票

当您发出需要JSON响应的请求时,它将为您提供JSON响应。以下标头会触发JSON响应:

X-Requested-With: XMLHttpRequest

要么

X-PJAX: true

要么

Accept: */json or *+json

如果您不想要此标准行为,则可以在app/Exceptions/Handler.php覆盖异常处理程序。将render函数更改为此(这是来自vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php的直接副本,并且总是通过忽略请求标头返回whoops)

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if (method_exists($e, 'render') && $response = $e->render($request)) {
        return Router::toResponse($request, $response);
    } elseif ($e instanceof Responsable) {
        return $e->toResponse($request);
    }

    $e = $this->prepareException($e);

    if ($e instanceof HttpResponseException) {
        return $e->getResponse();
    } elseif ($e instanceof AuthenticationException) {
        return $this->unauthenticated($request, $e);
    } elseif ($e instanceof ValidationException) {
        return $this->convertValidationExceptionToResponse($e, $request);
    }

    return $this->prepareResponse($request, $e);
}

或者,在此处添加您自己的逻辑,以确定在给出不同标头时您希望返回的内容类型。

© www.soinside.com 2019 - 2024. All rights reserved.