Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Amrith's avatar

How to override NotFoundException

I want to customize not found exception. My effort was failed. please help me someone !

UserFinderController.php

 $isUserCreate = User::findorFail(910);  // 910 is Fake ID , so it throws NotFoundException

Exceptions/NotFoundException.php

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;

class NotFoundException extends Exception
{
    public function render(Exception $exception, Request $request)
    {
        return Response::json([
            'message' => 'Not foundiizzzzzzzzzzzzzzzz',
            'code' => 404,


        ], 404);
    }
}


Handler.php

...
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
..
 public function register()
    {

        $this->renderable(function (Exception $e, $request) {

            if ($request->wantsJson()) {

                if ($e instanceof NotFoundHttpException) {
                    return throw new NotFoundException();
                }

             

                return Response::json([
                    'myMessage 4' => $e->getMessage(),
                    'myCode' => 500
                ], 500);


            }

        }

        );


    }

Output

OST http://127.0.0.1:8000/api/auth/register

HTTP/1.1 500 Internal Server Error
Host: 127.0.0.1:8000
Date: Sat, 05 Feb 2022 03:50:28 GMT
Connection: close
X-Powered-By: PHP/8.0.13
Cache-Control: no-cache, private
Date: Sat, 05 Feb 2022 03:50:28 GMT
Content-Type: application/json
Access-Control-Allow-Origin: *

{
  "message": "App\Exceptions\NotFoundException::render(): Argument #1 ($exception) must be of type Exception.....
0 likes
1 reply

Please or to participate in this conversation.