Laravel 流明为5.6的控制器中未捕获NotFoundHttpException
我想用自定义json响应管理404错误 代码如下:Laravel 流明为5.6的控制器中未捕获NotFoundHttpException,laravel,exception,lumen,Laravel,Exception,Lumen,我想用自定义json响应管理404错误 代码如下: try { $registration = Registration::find($id); if ($registration == null) throw new NotFoundHttpException(); return response()->json($registration, HttpResponse::HTTP_OK); } cat
try {
$registration = Registration::find($id);
if ($registration == null) throw new NotFoundHttpException();
return response()->json($registration, HttpResponse::HTTP_OK);
} catch (NotFoundHttpException $e) {
return response()->json(['message' => 'Registration not found'], HttpResponse::HTTP_NOT_FOUND);
}
但它从未进入catch块,并返回HTML视图:
Sorry, the page you are looking for could not be found.
(1/1) NotFoundHttpException
in RoutesRequests.php line 226
at Application->handleDispatcherResponse(array(0))
in RoutesRequests.php line 164
at Application->Laravel\Lumen\Concerns\{closure}()
in RoutesRequests.php line 413
at Application->sendThroughPipeline(array(), object(Closure))
in RoutesRequests.php line 166
at Application->dispatch(null)
in RoutesRequests.php line 107
at Application->run()
in index.php line 28
at require('/Users/julien/Documents/Proyectos/jaumo/public/index.php')
in server.php line 147
我还尝试了注册::findOrFail($id)应该返回40个错误,但结果相同
我可以在Handler.php
中更改它:
public function render($request, Exception $e)
{
if ($e instanceof NotFoundHttpException) {
return response()->json('Not Found', HttpResponse::HTTP_NOT_FOUND);
}
return parent::render($request, $e);
}
但这并不是我想要的,这里的消息是静态的,我想在控制器中管理它
我还尝试将NotFoundHttpException::class
添加到$dontReport数组中,但它不起作用
为什么,以及如何返回自定义json响应。我发现了我的错误,是路由上的404,我有:
$router->get('/registrations/{id}', 'RegistrationController@show');
而不是
$router->get('/registration/{id}', 'RegistrationController@show');
所以,它从未进入控制器,这就是为什么它没有引发我的异常
谢谢你的帮助 您是否记得在顶部导入名称空间异常?您的意思是:
使用Symfony\Component\HttpKernel\exception\NotFoundHttpException代码>???在这种情况下,是的!