2

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.

3
  • return response()->json(['error' => 'Custom error message'], 500]); Commented Jun 15, 2020 at 8:52
  • Yeah, I know that. But the problem here is that I still have an Exception before my Try/Catch Commented Jun 15, 2020 at 8:54
  • why do you want to put this model call inside try, catch when this can be handled on the compile time as well,you can just check if the there exists a row for a given id Commented Jun 15, 2020 at 8:58

1 Answer 1

0

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');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.