Benjamin W
Benjamin W

Reputation: 2848

Laravel abort() not working inside try and catch

abort(403); <-- works fine, will display laravel abort page

try{
    $rows = DB::.......

    if ( !$Rows ) {
        abort(403);<-- this will become exception
    } else {

    }
} catch (Exception $e) {

}

I have a page when user request, if no rows I would like to use laravel abort(); to terminate the page.

however I have use try catch wrap my code, it will become catch an error and cause laravel abort() not working.

anyone how to fix this?

Upvotes: 1

Views: 2462

Answers (2)

Mihir Bhende
Mihir Bhende

Reputation: 9055

\Exception is the base class of all php exceptions. So when you are catching \Exception in try.. catch block, you are practically catching all exceptions.

when you do abort(403), laravel internally throws HttpException with statusCode 403.

If you see in laravel, HttpException extends php's \RuntimeException which indeed at the end extends \Exception class.

The solution would be to catch a specific exception instead of catching \Exception. For example, if you are worried about mysql connection, you can catch PDOException. It's always better to be specific about exceptions you are catching.

<?php 

try{
    $rows = DB::someaction()...;

    if (!$rows) {
        abort(403);
    }
    // Do stuff with $rows

}catch (PDOException $e) {
    // take action for specific exception
}

Upvotes: 2

Vajiheh Habibi
Vajiheh Habibi

Reputation: 479

try this code

      try{
        abort(403);
    } catch (\Exception $e) {

        if($e->getStatusCode()==403)
            abort(403);
    }

Upvotes: 3

Related Questions