Level 6
Have you imported the exception at the top of app/Exceptions/Handler.php?
Like this:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm having problems catching Exceptions in my Laravel/Sanctum/ SPA/API that uses Cahsier. I can catch Stripe exceptions in the handler method, but can't catch NotFoundHttpException.
In my controller I'm deliberately setting a query parameter that I know will fail to test the exception:
Controller
public function processCheckout(Request $request)
{
$plan = Plan::findOrFail(100);
$user = $user = auth()->user();
//If user has no subscriptions subscribe them to new plan
if($user->subscriptions->count() === 0){
$user->newSubscription($plan->name, $plan->stripe_plan_id)->create($request->payment_method['id']);
//return response([], 201);
}
}
When I turn on: APP_DEBUG=true I get this response:
{
"message": "No query results for model [App\Plan] 100",
"exception": "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
"file": "/Applications/MAMP/htdocs/saas-spa/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
"line": 222,
"trace": [
{
"file": "/Applications/MAMP/htdocs/saas-spa/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
"line": 198,
"function": "prepareException",
"class": "Illuminate\Foundation\Exceptions\Handler",
"type": "->"
},
{
"file": "/Applications/MAMP/htdocs/saas-spa/app/Exceptions/Handler.php",
"line": 85,
"function": "render",
"class": "Illuminate\Foundation\Exceptions\Handler",
"type": "->"
}, // and more
]
}
When I turn APP_DEBUG=false I get nothing as a response.
app/Exceptions/Handler.php
public function render($request, Throwable $exception)
{
if ($exception instanceof \Stripe\Exception\ApiErrorException) {
return response()->json([
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
$response = $this->handleException($request, $exception);
return $response;
}
public function handleException($request, Throwable $exception)
{
if ($exception instanceof MethodNotAllowedHttpException) {
return $this->errorResponse('The specified method for the request is invalid', 405);
}
if ($exception instanceof NotFoundHttpException) {
return $this->errorResponse('The specified URL cannot be found', 404);
}
if ($exception instanceof HttpException) {
return $this->errorResponse($exception->getMessage(), $exception->getStatusCode());
}
if (config('app.debug')) {
return parent::render($request, $exception);
}
return $this->errorResponse('Unexpected Exception. Try later', 500);
}
Why am I not able to output my custom error message?
Please or to participate in this conversation.