【发布时间】:2018-12-01 10:57:17
【问题描述】:
我修改了 Exceptions/Handler.php 的 render 方法,让它返回我自己的响应,而不是在发生任何错误时渲染 lumen 的错误页面。
这是我更新的渲染方法。
/**
* 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)
{
// return parent::render($request, $e);
return response()
->json([
'errors' => $e
]);
}
我希望它在 NotFoundHttpException 发生时返回我的响应,但 lumen 仍然显示其原始错误页面...
我知道我应该修改app/Exceptions/Handler.php,但是因为它没有按我的预期工作,所以我修改了vendor/laravel/lumen/app/Exceptions/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)
{
return response(['test'=> 'test']);
// return parent::render($request, $e);
}
它按我的预期工作(不显示错误页面但返回 json 响应)。
在 bootstrap/app.php 中,似乎正确设置为调用 App\Exceptions\Handler::class,而不是 laravel\lumen\app\Exceptions\Handler::class。
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
我已经尝试过重新安装 lumen 和我的 docker 环境。 并且我尝试在安装lumen之后修改Handler.php(即应用中没有其他修改),但它不起作用。
有人知道我的更改没有反映吗??
【问题讨论】:
-
现在我知道什么对我的代码不利。在我的 bootstrap/app.php 中,我写了
require_once __DIR__.'/../../vendor/autoload.php';,但我在这里改为require_once __DIR__.'/../vendor/autoload.php';,它可以工作并且我的 Handler.php 被调用了!