无法在拉拉维尔上捕捉"SymfonyComponentHttpKernelExceptionNotFoundHttpException"



我正在使用此路由的路由模型绑定:

api.php

Route::group(['middleware' => ['auth:api']], function () {
Route::apiResource('applications', 'ApplicationController')->except(['index']);
});

和型号:

应用程序

/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName(): string
{
return 'client_id';
}

这是我的路线列表的一部分:

| GET | HEAD | api/v1/applications/{application} | vms-direct-debit.applications.show  | AppHttpControllersApplicationController@show  | api,auth:api |

其中,client_id是一个字符串,并且假设testclientapplications表中不存在。好吧,当我在postmaninsomnia:base_url/applications/testclient(GET,show(上调用此路由时,它会抛出一个SymfonyComponentHttpKernelExceptionNotFoundHttpException异常AS I WANT

好的,我想捕捉这个异常,所以我在app/Exceptions/Handler.php:上使用这个代码

public function render($request, Exception $exception)
{
if ($exception instanceof SymfonyComponentHttpKernelExceptionNotFoundHttpException) {
return response()->json([
'my-goddamn-custom' => 'message-here',
]);
}
return parent::render($request, $exception);
}

但我无法捕捉到我的自定义响应消息。如何获取自定义消息响应?

我自己解决了。

我使用了IlluminateDatabaseEloquentModelNotFoundException而不是SymfonyComponentHttpKernelExceptionNotFoundHttpException异常。

app/Exceptions/Handler.php:

use IlluminateDatabaseEloquentModelNotFoundException;
/**
* Render an exception into an HTTP response.
*
* @param  Request $request
* @param Exception $exception
*
* @return Response|SymfonyComponentHttpFoundationResponse
*/
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'my-goddamn-custom' => 'message-here',
]);
}
return parent::render($request, $exception);
}

最新更新