Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hsntngr's avatar

How to redirect users to another page with session messages while error occuring

I want to redirect users to admin page when any error occuring about the thujohn/twitter package. It throws Runtimeexception..

So I add couple code handler.php

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

    if ($exception instanceof \RuntimeException) {
        return redirect()->route('admin.panel')
            ->with('message', 'Please try again later..')
            ->with('message_type','warning');

    } else {
        return parent::render($request, $exception);
    }
}

But when I say that, it redirects user at all exceptions even at 404 errors or Trying to get property of non-object erros.. How can I fix this ? I want to redirect user for just relevant error

Or is there any way to do redirect user with condition like below.

if($exception->code == 436){
  // it says member has protected access. I can't use it code property outside of the exception class
      return redirect()->route('admin.panel')
            ->with('message', 'Specific error message')
            ->with('message_type','warning');

 }
0 likes
1 reply
bobbybouwmann's avatar
Level 88

Well, almost all exceptions extend the \RuntimeException class. Because of this most exceptions will be caught in your code.

Instead you need to wrap the code for twitter in a try catch and catch the exception there. If something went wrong you can simply throw a new exception and catch that exception instead.

try {
    // Do your twitter stuff here!
} catch (\RuntimeException $exception) {
    throw new TwitterFailedException();
}

In your handler you can do something like this

if ($exception instanceof \TwitterFailedException) {
    return redirect()->route('admin.panel')
        ->with('message', 'Please try again later..')
        ->with('message_type','warning');
}
1 like

Please or to participate in this conversation.