Laravel 5: Handle exceptions when request wants JSON

前端 未结 8 1605
野的像风
野的像风 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:59

    Using @Jonathon's code, here's a quick fix for 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);
    }
    

提交回复
热议问题