Catch errors with Laravel API Resource

Viewed 838

I'm trying to use Laravel API Resource and handle the error message by sending a specific HTTP code

Here is my code :

public function show($id)
{

    try {
        return FruitResource::make(Fruit::find($id));
    }
    catch(Exception $e)
    {
        throw new HttpException(500, 'My custom error message');
    }
}

My try/catch is systematically ignored when I try to access the route.

I am voluntarily accessing an object that is not in the database. I have ErrorException with message Trying to get property 'id' of non-object.

I would like to be able to send my own Exception here, in case the user tries to access data that doesn't exist. And return a json error.

1 Answers

Try this (notice the \ before Exception):

public function show($id)
{

    try {
        return FruitResource::make(Fruit::find($id));
    }
    catch(\Exception $e)
    {
        throw new HttpException(500, 'My custom error message');
    }
}
Related