Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Request Object in Error Handler Laravel

In my Laravel 5.2 project, I have a middleware happily storing requests and responses to DB or files. There I serialize/json_encode $request object for logging everything going on. (cookies, input, files, headers...)

I need to create an error handler that will use whole request object to include everything about request into the report email. But ExceptionHandler::report() does not accept Request as a parameter.

like image 861
hctopcu Avatar asked Jan 25 '16 15:01

hctopcu


2 Answers

Laravel 5.2 provides the helper method request(), which works for this use case:

/**
 * Report or log an exception.
 *
 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
 *
 * @param  \Exception  $exception
 * @return void
 */
public function report(Exception $exception)
{
    $request = request();

    parent::report($exception);
}
like image 88
Bryan Avatar answered Oct 12 '22 10:10

Bryan


In App\Exceptions\Handler.php and the render method wich does have the request as parameter. here you could fire an event to store the stuff in a session or database.

For example:

public function render($request, Exception $e)
    {
        if ($e instanceof HttpException) {
            if ($e->getStatusCode() == 403) {
                Event::fire(new UserNotAllowed($request));
                return redirect()->to("/home");
            }
            if ($e->getStatusCode() == 404) {
                if (Auth::guest()) {
                    return redirect()->to("/");
                }
            }
        }
        if ($e instanceof ModelNotFoundException) {          
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }
        return parent::render($request, $e);
    }

more info here.

like image 45
Joost Avatar answered Oct 12 '22 11:10

Joost