Laravel 5: Handle exceptions when request wants JSON

前端 未结 8 1715
野的像风
野的像风 2021-01-30 05:30

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

When I try to upload a file that is too big (Bigger than

8条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 05:50

    Building on @Jonathon's handler render function, I would just modify the conditions to exclude ValidationException instances.

    // If the request wants JSON + exception is not ValidationException
    if ($request->wantsJson() && ( ! $exception instanceof ValidationException))
    

    Laravel 5 returns validation errors in JSON already if appropriate.

    The full method in 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);
    }
    

提交回复
热议问题