Home > database >  Instruct Laravel to catch Class X not found
Instruct Laravel to catch Class X not found

Time:05-10

Consider we reference a non existing class in the console context (tinker/tinkerwell etc):

Anything::method();

This will give PHP Error: Class "Anything" not found ....

Is there some way I can instruct the Laravel framework to catch these errors "globally" and let a handler do something? It is not an alternative to insert try/catch in the code to be executed in tinker.

CodePudding user response:

Laravel docs provides a section destinated to error handling:

https://laravel.com/docs/9.x/errors

Where you can set up custom behaviors to exceptions, like send it to a custom view when happens exact error:

https://laravel.com/docs/9.x/errors#rendering-exceptions

use App\Exceptions\InvalidOrderException;
 
/**
 * Register the exception handling callbacks for the application.
 *
 * @return void
 */
public function register()
{
    $this->renderable(function (InvalidOrderException $e, $request) {
        return response()->view('errors.invalid-order', [], 500);
    });
}

CodePudding user response:

These errors are fairly easy to use static code analysis to find. In my opinion no code should be shipped to production, with an unknown class error.

The tool the community uses for this at the moment is larastan. It has more advanced features, and works in a level range from 0 to 9, in your case rule level 0 will be more than enough to find these problems.

composer require nunomaduro/larastan:^2.0 --dev

Create a config file in the root named phpstan.neon.

includes:
    - ./vendor/nunomaduro/larastan/extension.neon

parameters:

    paths:
        - app

    level: 0

You can analyze your code, and find these errors.

./vendor/bin/phpstan analyse
  • Related