我想通过自定义json响应来管理404错误。
代码如下:
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
我还尝试了Registration::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响应。
答案 0 :(得分:0)
我发现我的错误,这是路线上的404,我遇到了
$router->get('/registrations/{id}', 'RegistrationController@show');
代替
$router->get('/registration/{id}', 'RegistrationController@show');
因此,它永远不会进入控制器,这就是为什么它没有引起我的异常。
感谢您的帮助!