why redirect don't work into try catch?

ijurij
Member | 4
+
0
-

After form submit this code executed:

#[Requires(methods: 'POST', sameOrigin: true)]
    private function processSignUpForm(Form $form, \stdClass $data): void
    {
        try {
            $data->roles = 'client';
            $this->userfacade->add($data);
            $this->flashMessage('message', 'success');
            $this->redirect(':in'); // it NOT work here
        } catch (\Throwable $th) {
            $form->addError($th->getMessage());
        }
		$this->redirect(':in'); // it work here, but error only in flashMessage and user get out from register page
    }

Into $this->userfacade->add($data);:

#[Requires(methods: 'POST', sameOrigin: true)]
    public function add($data): void // object
    {
        $this->db->beginTransaction();
        try {
            $new_user = $t->insert($data);
            $this->db->commit();
        } catch (UniqueConstraintViolationException $e) {
            $this->db->rollBack();
            throw new \Exception('UniqueConstraintViolationException');
        } catch (Nette\Database\DriverException $e) {
            $this->db->rollBack();
            throw new \Exception('Nette\Database\DriverException');
        }
    }

Into try-catch redirect not work. After catch redirect work but user get out from register page and errors can only be passed through flashMessage.

Please why and how to make it work inside try catch block…

Marek Bartoš
Nette Blogger | 1281
+
+5
-

Redirect works via throwing an exception (Nette\Application\AbortException). Catching it cancels the redirect.

You can e.g. use return; in the catch block instead.


It is (usually) bad idea to catch Throwable (without re-throwing it). Most errors are programmatical and should be logged and reported to the developer. They are useless for the user and may even leak sensitive information. Never send message from Throwable to the user.

Ideally always catch specific exceptions that you know may occur and shouldn't make the application fail completely. If they are programmatical – log them. If they represent user error that user should be notified about – create an exception class (extending generic Exception) with clear name (e.g. AccountBalanceTooLow) explaining what exactly went wrong with the interaction and inform user in a way helpful to them.

Last edited by Marek Bartoš (2025-01-07 00:22)

ijurij
Member | 4
+
0
-

I missed it

Redirect works via throwing an exception

catch Throwable (without re-throwing it) – yes, bad. It is the beginning of writing :)

Thank you for little theory.