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.

Jeremy
  • 1,756
  • 3
  • 21
  • 45
  • ```return response()->json(['error' => 'Custom error message'], 500]);``` – Ashish Rawat Jun 15 '20 at 08:52
  • Yeah, I know that. But the problem here is that I still have an Exception before my Try/Catch – Jeremy Jun 15 '20 at 08: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 – Ashish Rawat Jun 15 '20 at 08:58

1 Answers1

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');
    }
}
Qumber
  • 13,130
  • 4
  • 18
  • 33