[英]Can not catch "Symfony\Component\HttpKernel\Exception\NotFoundHttpException" on laravel
I am using route model binding for this route:我正在为此路由使用路由模型绑定:
api.php api.php
Route::group(['middleware' => ['auth:api']], function () {
Route::apiResource('applications', 'ApplicationController')->except(['index']);
});
and on the model:并在模型上:
Application应用
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName(): string
{
return 'client_id';
}
Here is part of my route-list:这是我的路线列表的一部分:
| GET | HEAD | api/v1/applications/{application} | vms-direct-debit.applications.show | App\Http\Controllers\ApplicationController@show | api,auth:api |
In which, client_id
is a string and suppose that testclient
DOES NOT EXIST in applications
table.其中,
client_id
是一个字符串,假设testclient
不存在于applications
表中。 Well, when I call this route on postman
or insomnia
: base_url/applications/testclient
( GET
, show), it throws a Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException
Exception AS I WANT .好吧,当我呼吁这条路线
postman
或insomnia
: base_url/applications/testclient
( GET
,显示),它抛出一个Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException
例外,因为我想要的。
Okay, I want to catch this exception, so I use this code on app/Exceptions/Handler.php
:好的,我想捕捉这个异常,所以我在
app/Exceptions/Handler.php
上使用这个代码:
public function render($request, Exception $exception)
{
if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return response()->json([
'my-goddamn-custom' => 'message-here',
]);
}
return parent::render($request, $exception);
}
But I can not catch my custom response message.但我无法捕捉到我的自定义响应消息。 How can I catch my custom message response?
如何捕捉我的自定义消息响应?
I solved it myself.我自己解决了。
I used Illuminate\\Database\\Eloquent\\ModelNotFoundException
instead of Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException
exception.我使用
Illuminate\\Database\\Eloquent\\ModelNotFoundException
而不是Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException
异常。
app/Exceptions/Handler.php :应用程序/异常/Handler.php :
use Illuminate\Database\Eloquent\ModelNotFoundException;
/**
* Render an exception into an HTTP response.
*
* @param Request $request
* @param Exception $exception
*
* @return Response|\Symfony\Component\HttpFoundation\Response
*/
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'my-goddamn-custom' => 'message-here',
]);
}
return parent::render($request, $exception);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.