Home > Software design >  How to avoid errors on nonfound model in method with model class as parameter?
How to avoid errors on nonfound model in method with model class as parameter?

Time:11-25

When in laravel 8 I define destroy method with model class as parameter

public function destroy(Ad $ad)
{
    $ad->delete();

    return [];
}

on request in POSTMAN with non existing Ad I got not only 404 error code, but also error messages :

"message": "No query results for model [App\\Models\\Ad] 6",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file": "/project//vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
"line": 385,
"trace": [
    {
        "file": "/project//vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
        "line": 332,
        "function": "prepareException",
        "class": "Illuminate\\Foundation\\Exceptions\\Handler",
        "type": "->"
    },
    

If there is a way to deal it not to get errors in in POSTMAN output ?

Thanks in advance !

CodePudding user response:

public function destroy(Ad $ad): array 
{
    try{ 
       $ad->delete();
    } catch(ModelNotFoundException $modelNotFoundException) {
       // do something herereturn [];
}

You could catch the ModelNotfoundException here.

CodePudding user response:

If you want to remove the extra detail from the body of the response, you can simply set APP_DEBUG=false.

If you also want to remove the message as well you can do this in your app/Exceptions/Handler.php class by overriding the render method:

use Illuminate\Database\Eloquent\ModelNotFoundException; // <-- add to the top of the class

public function render($request, Throwable $e)
{
    if ($e instanceof ModelNotFoundException && $request->wantsJson()) {
        return response('steve', 404);
    }

    return parent::render($request, $e);
}

Alternatively, if you also want to remove the message from the body for all NotFoundHttpExceptions, you could instead add the following to the register method:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; // <-- add to the top of the class

$this->renderable(function (NotFoundHttpException $e, $request) {
    if ($request->wantsJson()) {
        return response('', 404);
    }
});

This will only change the result for JSON responses, the standard 404 page will still be used for non-JSON responses.

NB At the time of writing, you can't use the renderable method for intercepting a ModelNotFoundException as it gets converted to a NotFoundHttpException in the prepareException method before the renderable callbacks are executed.


  • Related