0

I am trying to throw a NotFoundResourceException in Laravel programmatically

  use Symfony\Component\Translation\Exception\NotFoundResourceException;
  
  throw new NotFoundResourceException('The Item you could not be found', 404);

From the code editor I can see the hint that the second parameter is the code but this returns status 500 instead of 404 enter image description here

throw new NotFoundResourceException('The Item you could not be found'); without the parameter also returns status 500

I can use abort(404) as suggested in How to make Laravel 5 return 404 status code but is there a way to throw 404 error?

Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74

1 Answers1

1

Look like you have imported wrong one NotFoundResourceException instead of NotFoundHttpException

NotFoundResourceException extended from Exception

public function __construct($message = "", 
                            $code = 0,
                           Throwable $previous = null
                          ) 

So it wont throw http exception .

If you look at implementation of NotFoundHttpException which is extended from HttpException .Constructor has

     public function __construct(?string $message = '', 
                                  \Throwable $previous = null, 
                                   int $code = 0, 
                                   array $headers = []
                                 )

So it accept second argument as $previous exception

try {
        test();
    } catch(Error $e) {

        throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException("not found pagew",$e,404);
    }

Now if we catch error in App\Exceptions\Handler

public function render($request, Throwable $e)
    {
        if($e instanceof NotFoundHttpException){
            dump($e->getMessage());
            dump($e->getCode());
            dd($e->getPrevious());

        }

        return parent::render($request, $e); // TODO: Change the autogenerated stub
    }

it will print like below

"not found pagew"

404

Error {#353 ▼ #message: "Call to undefined function test()" #code: 0 #file: "I:\xampp\htdocs\adbs\live\sra\routes\web.php" #line: 28 trace: {▶} }

John Lobo
  • 14,355
  • 2
  • 10
  • 20