Laravel 5:请求JSON时处理异常 [英] Laravel 5: Handle exceptions when request wants JSON

查看:495
本文介绍了Laravel 5:请求JSON时处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Laravel 5上通过AJAX进行文件上传。除了一件事,我已经有很多工作了。

I'm doing file uploads via AJAX on Laravel 5. I've got pretty much everything working except one thing.

当我尝试上传一个文件太大了(比 upload_max_filesize post_max_size 我得到一个TokenMismatchException抛出。

When I try to upload a file that is too big (Bigger than upload_max_filesize and post_max_size I get a TokenMismatchException thrown.

这是预期的,因为我知道如果这些限制被超出,我的输入将为空。空输入意味着没有收到 _token 因此,为什么负责验证CSRF令牌的中间件正在匆匆开始。

This is to be expected however, because I know that my input will be empty if these limits are being exceeded. Empty input, means no _token is received hence why the middleware responsible for verifying CSRF tokens is kicking up a fuss.

然而,我的问题不在于抛出异常,它是如何呈现的。当这个例外被Laravel抓住时,它会吐出通用的Whoops页面的HTML(从调试模式开始,堆栈跟踪的负载)。

My issue however is not that this exception is being thrown, it is how it is being rendered. When this exception is being caught by Laravel it's spitting out the HTML for the generic Whoops page (With a load of stack tracing since I'm in debug mode).

什么是处理此异常的最佳方法,以便通过AJAX返回JSON(或者在请求JSON时),同时保留默认行为otherw ise?

What's the best way to handle this exception so that JSON is returned over AJAX (Or when JSON is requested) while keeping the default behaviour otherwise?

编辑:这似乎发生,无论抛出的异常如何。我刚刚尝试通过AJAX(数据类型:JSON)向页面发出请求,该页面不存在以获取404,同样的事情发生 - 返回HTML,没有JSON友好。

This seems to happen regardless of the exception thrown. I've just tried making a request via AJAX (Datatype: JSON) to a 'page' that doesn't exist in an attempt to get a 404 and the same thing happens - HTML is returned, nothing JSON friendly.

推荐答案

我将会考虑到@Wader的回答和@Tyler Crompton的评论,

I'm going to take a shot at this one myself taking into account the answer given by @Wader and the comments from @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);
}

这篇关于Laravel 5:请求JSON时处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆