Search code examples
phpsessionlaravel-5.3

Redirect with exception variable


I have the following (test) setup:

web.php

Route::get("test/test","TestController@test");
Route::get("test/numeric","TestController@numeric");
Route::get("forbidden", "TestController@exception")

TestController.php

use \Symfony\Component\HttpKernel\Exception\HTTPException; 
public class TestController {

public function test() {
    return redirect()->to("/forbidden")->with("exception",new HttpException(403));            
}

public function numeric() {
    return redirect()->to("/forbidden")->with("exception",403);            
}

public function exception() {
    if (\Session::get("exception") instanceof \Throwable) {
        throw \Session::get("exception"); //Let the default handler handle it.
    } else if (is_numeric(\Session::get("exception"))) {
        throw new HttpException(\Session::get("exception"));
    } else {
        return "Empty exception";
    }
}
}

When I navigate to /test/test I always get "Empty exception" to appear. However /test/numeric shows the exception normally. Furthermore I've checked the contents of the session in both cases, in the first case the exception object is not passed at all.

Am I missing something obvious here?


Solution

  • After a lot more digging through I've realised that this is impossible to do because of the exception stack trace. There's a lot of functions which take in closures as parameters and because of that the exception stack trace is not serializable. Laravel seems to quietly drop any non-serializable variables from the session.