1. 程式人生 > >關於Laravel 自定義HTTP錯誤(404,500等錯誤)

關於Laravel 自定義HTTP錯誤(404,500等錯誤)

使用Dingo:

1、在......\vendor\dingo\api\src\Exception\Handler.php中修改建構函式

2、將.env檔案中的API_DEBUG改為false

不使用Dingo:

修改....\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(config('app.debug')) {
            $replacements = [];
            $error = $this->convertExceptionToResponse($exception);
            $statusCode = $error->getStatusCode($exception);
            if (! $message = $exception->getMessage()) {
                $message = sprintf('%d %s', $statusCode, Response::$statusTexts[$statusCode]);
            }
            $replacements = [
                'errcode' => $statusCode,
                'errdesc' => $message,
            ];
            if ($exception instanceof MessageBagErrors && $exception->hasErrors()) {
                $replacements['errors'] = $exception->getErrors();
            }
            if ($code = $exception->getCode()) {
                $replacements['code'] = $code;
            }
            if (!config('app.debug')) {
                $replacements['debug'] = [
                    'line' => $exception->getLine(),
                    'file' => $exception->getFile(),
                    'class' => get_class($exception),
                    'trace' => explode("\n", $exception->getTraceAsString()),
                ];
            }
            return response($replacements,$statusCode);
        }
        return parent::render($request, $exception);
    }