Symfony – Exception message based on result

In my Symfony project I have performed simple password validation check.

What I am trying to do is to catch the Exception based on the message that is echoed in that method.

I have trouble figuring out how to implement that.

This is my pass check method:

public function validatePasswordStrength($password, $username): void
{
    $error = null;

    if ($password === '') {
        echo "Password not entered!";
    } elseif ($password === $username) {
        echo "Password and username can not be same!";
    } elseif (strlen($password) < 8) {
        echo "Password must be at least 8 characters long!";
    } elseif (!preg_match("#[a-z]+#", $password)) {
        echo "Password must include at least one lowercase letter!";
    } elseif (!preg_match("#[A-Z]+#", $password)) {
        echo "Password must include at least one uppercase letter!";
    } elseif (!preg_match("#W+#", $password)) {
        echo "Password must include at least one symbol!";
    }

    if ($error) {
        throw new Exception('Here I want to put echo message.');
    }
}

Actually the idea is to define any of this message and if statement is true thenthe Exception message should be the message from that statement. This was the idea.

And this is my endpoint method in Controller:

/**
 * @Route("/check-password", name="check_password")
 */
public function validatePassword(Request $request, $password = 'S0235ds-')
{
    $username = 'Apple';

    try {
        $this->methodService->validatePasswordStrength($password, $username);

        return $this->json(["message" => "SUCCESS"]);
    } catch (Exception $e) {
        return $this->json(["message" => $e->getMessage()], Response::HTTP_BAD_REQUEST);
    }
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *