我正在 Laravel 5 上通过 AJAX 进行文件上传。除了一件事之外,我几乎一切都正常。
当我尝试上传太大的文件时(大于upload_max_filesize
and post_max_size
我抛出了 TokenMismatchException。
但这是预料之中的,因为我知道如果超出这些限制,我的输入将为空。输入空,表示没有_token
因此,负责验证 CSRF 令牌的中间件会大惊小怪。
然而,我的问题不是抛出这个异常,而是它的渲染方式。当 Laravel 捕获此异常时,它会吐出通用 Whoops 页面的 HTML(由于我处于调试模式,因此带有大量堆栈跟踪)。
处理此异常的最佳方法是什么,以便通过 AJAX (或请求 JSON 时)返回 JSON,同时保持默认行为?
Edit:无论抛出异常,这似乎都会发生。我刚刚尝试通过 AJAX(数据类型:JSON)向不存在的“页面”发出请求,试图获取 404,结果发生了同样的事情 - 返回了 HTML,没有任何 JSON 友好的内容。
考虑到 @Wader 给出的答案和 @Tyler Crompton 的评论,我将自己尝试一下:
应用程序/异常/Handler.php
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// If the request wants JSON (AJAX doesn't always want JSON)
if ($request->wantsJson()) {
// Define the response
$response = [
'errors' => 'Sorry, something went wrong.'
];
// If the app is in debug mode
if (config('app.debug')) {
// Add the exception class name, message and stack trace to response
$response['exception'] = get_class($e); // Reflection might be better here
$response['message'] = $e->getMessage();
$response['trace'] = $e->getTrace();
}
// Default response of 400
$status = 400;
// If this exception is an instance of HttpException
if ($this->isHttpException($e)) {
// Grab the HTTP status code from the Exception
$status = $e->getStatusCode();
}
// Return a JSON response with the response array and status code
return response()->json($response, $status);
}
// Default to the parent class' implementation of handler
return parent::render($request, $e);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)