我在Laravel 5上通过AJAX上传文件。除了一件事之外,我几乎所有工作都在工作。
当我尝试上传太大的文件(大于upload_max_filesize
和post_max_size
时,我会抛出TokenMismatchException。
然而,这是预料之中的,因为我知道如果超出这些限制,我的输入将为空。空输入,表示没有收到_token
,因此负责验证CSRF令牌的中间件为什么会大惊小怪。
然而,我的问题不是抛出这个异常,而是渲染它的方式。当Laravel捕获到这个异常时,它会为通用的Whoops页面吐出HTML(由于我在调试模式下有一堆堆栈跟踪)。
处理此异常的最佳方法是什么,以便通过AJAX返回JSON(或者在请求JSON时),同时保留默认行为?
编辑:无论抛出什么异常,这似乎都会发生。我刚试过通过AJAX(数据类型:JSON)向“'页面”发出请求。在尝试获取404时并不存在,同样的事情发生 - 返回HTML,没有JSON友好。
答案 0 :(得分:80)
考虑到@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);
}
答案 1 :(得分:11)
在您的应用中,您应该app/Http/Middleware/VerifyCsrfToken.php
。在该文件中,您可以处理中间件的运行方式。所以你可以检查请求是否是ajax并处理你喜欢的方式。
另外,也许是一个更好的解决方案,就是编辑异常处理程序以返回json。请参阅app/exceptions/Handler.php
,类似下面的内容将是一个起点
public function render($request, Exception $e)
{
if ($request->ajax() || $request->wantsJson())
{
$json = [
'success' => false,
'error' => [
'code' => $e->getCode(),
'message' => $e->getMessage(),
],
];
return response()->json($json, 400);
}
return parent::render($request, $e);
}
答案 2 :(得分:8)
在@ Jonathon的处理程序渲染功能的基础上,我只想修改条件以排除ValidationException实例。
// If the request wants JSON + exception is not ValidationException
if ($request->wantsJson() && ( ! $exception instanceof ValidationException))
如果合适,Laravel 5已经在JSON中返回验证错误。
App / Exceptions / Handler.php中的完整方法:
/**
* 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 the request wants JSON + exception is not ValidationException
if ($request->wantsJson() && ( ! $exception instanceof ValidationException))
{
// 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($exception); // Reflection might be better here
$response['message'] = $exception->getMessage();
$response['trace'] = $exception->getTrace();
}
// Default response of 400
$status = 400;
// If this exception is an instance of HttpException
if ($this->isHttpException($exception))
{
// Grab the HTTP status code from the Exception
$status = $exception->getCode();
}
// Return a JSON response with the response array and status code
return response()->json($response, $status);
}
return parent::render($request, $exception);
}
答案 3 :(得分:6)
我已经改变了几个在Laravel 5.3上工作的实现。 主要区别在于我的将返回正确的HTTP状态文本
在app \ Exceptions \ Handler.php的render()函数中,将此代码段添加到顶部:
if ($request->wantsJson()) {
return $this->renderExceptionAsJson($request, $exception);
}
renderExceptionAsJson的内容:
/**
* Render an exception into a JSON response
*
* @param $request
* @param Exception $exception
* @return SymfonyResponse
*/
protected function renderExceptionAsJson($request, Exception $exception)
{
// Currently converts AuthorizationException to 403 HttpException
// and ModelNotFoundException to 404 NotFoundHttpException
$exception = $this->prepareException($exception);
// Default response
$response = [
'error' => 'Sorry, something went wrong.'
];
// Add debug info if app is in debug mode
if (config('app.debug')) {
// Add the exception class name, message and stack trace to response
$response['exception'] = get_class($exception); // Reflection might be better here
$response['message'] = $exception->getMessage();
$response['trace'] = $exception->getTrace();
}
$status = 400;
// Build correct status codes and status texts
switch ($exception) {
case $exception instanceof ValidationException:
return $this->convertValidationExceptionToResponse($exception, $request);
case $exception instanceof AuthenticationException:
$status = 401;
$response['error'] = Response::$statusTexts[$status];
break;
case $this->isHttpException($exception):
$status = $exception->getStatusCode();
$response['error'] = Response::$statusTexts[$status];
break;
default:
break;
}
return response()->json($response, $status);
}
答案 4 :(得分:0)
使用@ Jonathon的代码,这里是Laravel / Lumen 5.3的快速修复:)
/**
* 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 ($e instanceof HttpException)
{
// 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);
}
答案 5 :(得分:0)
您可以轻松捕获err.response,如下所示:
axios.post().then().catch(function(err){
console.log(err.response); //is what you want
};
答案 6 :(得分:0)
我的方式:
// App\Exceptions\Handler.php
public function render($request, Throwable $e) {
if($request->is('api/*')) {
// Setting Accept header to 'application/json', the parent::render
// automatically transform your request to json format.
$request->headers->set('Accept', 'application/json');
}
return parent::render($request, $e);
}
答案 7 :(得分:0)
在 Laravel 8.x 中,你可以这样做
app/Http/Exceptions/Handler.php
public function render($request, Throwable $exception)
{
if ($request->wantsJson()) {
return parent::prepareJsonResponse($request, $exception);
}
return parent::render($request, $exception);
}
如果您想始终为所有异常返回 JSON,只需删除条件并始终调用 parent::render
并始终调用 parent::prepareJsonResponse
。
当使用 APP_DEBUG=true
呈现 JSON 时,您将获得完整的错误报告和堆栈跟踪。当 APP_DEBUG=false
时,您将收到一条通用消息消息,仅此而已。
答案 8 :(得分:-2)
快速注释...在Laravel 5.5中,异常在方法中命名为“$ exception”而不是“$ e”。