Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - global exception handler for API requesting non-exist object

Tags:

php

laravel

I am using Laravel 5.3. I have few APIs where user will request for specific id. For example url to subscribe an event
example.com/api/event/{id}/subscribe

Normally if id not exist, Laravel will return response 500 with error message "Trying to get property of non-object"

So I would add check if event is exist like below in every controller where model 'id' id passed:

$event = Event::find($id)
if ($event) {
    // return json data
}
else {
    return response()->json([
        'status' => 'object not found'
    ], 404);
}

My question is, any better solution to handle this globally to check if object requested is not exist? My current solution is here, but I might think there should be better one

I add this code into my app/Exception/Handler.php, so every api request non-existing object will return 404 with specific json message. So the API consumer will know the object id not valid.

public function render($request, Exception $exception)
{
    // global exception handler if api request for non existing object id
    if ($request->wantsJson() && $exception->getMessage() == 'Trying to get property of non-object') {
        return response()->json([
            'status' => 'object requested not found'
        ], 404);
    }

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

Thanks in advance!

like image 225
xmhafiz Avatar asked Dec 15 '22 02:12

xmhafiz


1 Answers

You can use render() function of App\Exceptions\Handler class as:

public function render($request, Exception $exception)
{
    if ($request->wantsJson() && $exception instanceof ModelNotFoundException) {
        return response()->json(['status' => 'object requested not found'], 404);
    }

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

And remember to add following code:

use Illuminate\Database\Eloquent\ModelNotFoundException;

Docs

like image 148
Amit Gupta Avatar answered May 09 '23 11:05

Amit Gupta