Search code examples
phplaravelsessionreportsession-variables

Session store error when retrieving and saving data to the session at controller and retrieving at handler Laravel 5.5


I'm handling exceptions at Handler.php, but when I provoke certain exception on purpose, the report method not only writes that exception, it also writes at least 24 time the same Session store error, because I'm using the session to retrieve the a customize error message. My report method only has the default parent::report($exception);. The log writes the Query error I'm making on purpose, but also a lot of those Session store error

//render method at Handler.php 

public function render($request, Exception $exception)
    {

        if($request->session()->has('errorOrigin'))
        {
            $errorOrigin = $request->session()->pull('errorOrigin');
        } else{
            $errorOrigin = "";
        }

        //session()->forget('errorOrigin');
        //return dd(session());
        //return parent::render($request, $exception);

        //this return is just some trying
        //return parent::render($request, $exception);
        //return dd($exception);
        //return parent::render($request, $exception);

        //just in case someone throws it but don´t has the try catch at the code
        if($exception instanceof \App\Exceptions\CustomException) {
            //$request->session()->flash('message_type', 'negative');
            \Session::flash('message_type', 'negative');
            \Session::flash('message_icon', 'hide');
            \Session::flash('message_header', 'Success');
            \Session::flash('error', '¡Ha ocurrido un error ' . $errorOrigin . "!" 
            .' Si este persiste contacte al administrador del sistema');
            return redirect()->back();

        }elseif($exception instanceof \Illuminate\Database\QueryException) {
            \Session::flash('message_type', 'negative');
            \Session::flash('message_icon', 'hide');
            \Session::flash('message_header', 'Success');
            \Session::flash('error', '¡Ha ocurrido un error en la consulta ' . $errorOrigin);//this is he customized error message
            return back();

 }else{/*Original error handling*/
            return parent::render($request, $exception);
        }
    }


//Method at my controller
public function index(Request $request)
    {


            //custom message if this methods throw an exception
            \Session::put('errorOrigin', " mostrando los clientes");

                //on purpose error, that table doesn´t exist, so it causes the QueryException error
        DB::table('shdhgjd')->get();
}

I think all those \Session or the errorOrigin variable retrieved create the error Session store error, but I need them, is there a logic/syntax error? I need some help, because the log is growing giant, and it doesn't have sense to save all those errors, neither just don't save them.

Also found out that this error is happening on every page, event at login. I login with username instead of email (of course the login already works and it logins properly with username). Does it have something to do about it? I refresh login page without doing anything, not event trying to log in and it also saves an error at my log, but my app keep working.

This time I'm provoking on purpose the error from the non exist database table, this is a summary of the errors that are saved to the log when i ONCE provoke the error. As you will see, the session store error or similar repeats, but some show a uncaught RunTimeException. Also added the stack-trace of the last one. The session store error repeats at least like 24 times or even more.

[2019-06-06 19:55:59] local.ERROR: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'prisma.shdhgjd' doesn't exist (SQL: select * from `shdhgjd`) 

[2019-06-06 19:56:00] local.ERROR: Session store not set on request. {"exception":"[object] (RuntimeException(code: 0): Session store not set on request. at C:\\ProyectoPrisma_BS3\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Request.php:419)
[stacktrace]
"#0" C:\\ProyectoPrisma_BS3\\app\\Exceptions\\Handler.php(69): Illuminate\\Http\\Request->session()

[2019-06-06 19:56:00] local.ERROR: Session store not set on request. {"exception":"[object] (RuntimeException(code: 0): Session store not set on request. at C:\\ProyectoPrisma_BS3\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Request.php:419)
[stacktrace]

[2019-06-06 19:56:00] local.ERROR: Uncaught RuntimeException: Session store not set on request. in C:\ProyectoPrisma_BS3\vendor\laravel\framework\src\Illuminate\Http\Request.php:419
Stack trace:
"#0" C:\ProyectoPrisma_BS3\app\Exceptions\Handler.php(69): Illuminate\Http\Request->session()

Solution

  • The error is being thrown by the call to $request->session() because it doesn't have a session object.

    A request object is given a session via the StartSession middleware. This middleware is included in the web middleware group, that's automatically given to all routes inside routes/web.php.

    It's possible you're using a route that hasn't established any session use, like an API route or just one where you forgot the web middleware group.

    And because an error is occurring in the error handler, it's becoming a loop. ERROR > HANDLER > ERROR > HANDLER > and so on...

    Typically I'd recommend handling all expected scenarios - including possible exceptions - in the controller. That way you aren't debugging the error handler wondering why a controller is giving a redirect you might not be expecting.

    That said, handling app-specific exceptions in the error handler and returning redirects or other custom responses is okay, so long as you're targeting specific exceptions and not using redirects and sessions for ALL exceptions.

    An example of how you might handle that:

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        // Create a specific path for your custom exception.
        if ($exception instanceof MyCustomException) {
            // Want to use sessions? Check if they're available.
            if ($request->hasSession()) {
                // ...
                return \redirect()->back();
            }
    
            // Sessions weren't available on this request. Create a different response.
            return view('errors.no-session-view');
        }
    
        // Use the default render response for everything else.
        return parent::render($request, $exception);
    }