Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Laravel exception handling for Tests

Tags:

tdd

laravel

I am following along this course testdrivenlaravel, and it mentions a way disable the Laravel's exception handling to prevent Laravel from handling exceptions that occur and instead throwing it, so we can get a more detailed error in our tests output.

So I added this method in my testcase class, and in the render method I am throwing the exception

protected function disableExceptionHandling() {

    $this->app->instance(Handler::class, new class extends Handler {
        public function __construct()
        {
        }
        public function report(\Exception $e)
        {
        }
        public function render($request, \Exception $e)
        {
            throw $e;
        }
    });
}

But whenever I call it in a test, to get more detailed error, I still get the same errors that Laravel Handler is rendering.

When I change the Handler class directly like this:

public function render($request, Exception $exception)
{
    throw $exception;
    // return parent::render($request, $exception);
}

I get the detailed errors, but I need to get the disableExceptionHandling helper work.

like image 201
Mubashar Abbas Avatar asked Jun 02 '18 10:06

Mubashar Abbas


People also ask

How do I disable error reporting in laravel?

By default, error detail is enabled for your application. This means that when an error occurs you will be shown an error page with a detailed stack trace and error message. You may turn off error details by setting the debug option in your app/config/app. php file to false .

What is exception handling in laravel?

Reporting ExceptionsAll exceptions are handled by the App\Exceptions\Handler class. This class contains a register method where you may register custom exception reporting and rendering callbacks.

How does laravel handle exception in API?

To do that, you can specify Route::fallback() method at the end of routes/api. php, handling all the routes that weren't matched. Route::fallback(function(){ return response()->json([ 'message' => 'Page Not Found. If error persists, contact [email protected]'], 404); });


1 Answers

Put this at the top of your test method:

    $this->withoutExceptionHandling();

You don't need to create a method for this, it's included in laravel's 'InteractsWithExceptionHandling' trait which is used by the abstract TestCase that you should be extending from your test.

like image 146
wheelmaker Avatar answered Sep 30 '22 20:09

wheelmaker