1

I am using route model binding for my API routes.

Route::middleware('client')->group(function(){
    Route::get('/documents/{document}', [DocumentController::class, 'get']);
    Route::apiResource('documents', DocumentController::class)->only('store', 'destroy');
    Route::post('filter', [DocumentController::class, 'filter']);
});

DocumentController:

public function get(Document $document): JsonResponse|string|null
{
    // do some stuff

    return response()->json([
        'code' => 404,
        "message" => "Some Message"
    ], 404);
}

When I access my API route (GET - /api/documents/$uuid) with valid $uuid that exist in DB everything works fine. But If I call it with invalid $uuid which doesn't exist in DB it throws exception:

"message": "No query results for model [App\\Models\\Document] some_uuid_here",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",

Problem is thrown exception is NotFoundHttpException while it should be ModelNotFoundException.

Shouldn't NotFoundHttpException need to get thrown if route completely undefined? I don't want to show user Route not defined while there is actual route but not record with given primary key.


I surrounded Document::findOrFail($value); in try catch block just to debug exception and even findOrFail throws NotFoundHttpException

try {
    Document::findOrFail($value);
}catch (\Exception $exception){
    throw $exception;
}

enter image description here

try {
    Document::findOrFail($value);
}catch (\Exception $exception){
    echo get_class($exception);
}

enter image description here

Vüsal Hüseynli
  • 889
  • 1
  • 4
  • 16
  • 1
    it is throwing a `ModelNotFoundException` ... which is then getting converted to another exception by the Exception Handler ...... `$e instanceof ModelNotFoundException => new NotFoundHttpException($e->getMessage(), $e),` – lagbox May 29 '23 at 12:51
  • @lagbox where? I didn't customize anything in Exception Handler – Vüsal Hüseynli May 29 '23 at 12:58
  • 1
    hehe, obviously it isn't something you are doing, it is done by default, otherwise I wouldn't have the code to show for it .... I don't know what you want to do with that exception but you would have to do something in the handler to deal with it at that level – lagbox May 29 '23 at 13:00
  • 1
    no, `findOrFail` does not throw that exception, it throws a `ModelNotFoundException` ... right from the `findOrfail` method: `throw (new ModelNotFoundException)` ... also directly from the source code https://github.com/laravel/framework/blob/9cef699bfc633a3d42840b47a377155feba3107c/src/Illuminate/Database/Eloquent/Builder.php#L473 – lagbox May 29 '23 at 13:02
  • @lagbox Both `Route not defined` and `Record not found` getting thrown by same class? Then how I am gonna know what caused problem. I need to customize exception messages – Vüsal Hüseynli May 29 '23 at 13:04

0 Answers0