PHP Catch exceptions run order - php

I have some try-catch exception and if statements in the code below that I am trying to write.
try {
$user = new User($userId);
if ($user->getEmailToken() == $emailToken) {
try {
$user->setEmailToken('');
$user->setEmailVerified(1);
$user->store()
fMessaging::create('success', 'verify', 'Your email has been verified. Thank you.');
fURL::redirect('/account/confirm.php');
} catch (fExpectedException $e) {
fMessaging::create('errorMessage', 'verify', $e->getMessage());
fMessaging::create('error', 'verify', "Your email could not be verified at this time, please be sure the link from the email was copied correctly.");
}
} else {
fMessaging::create('errorMessage', 'verify', 'User token does not match.');
fMessaging::create('error', 'verify', "Your email could not be verified at this time, please be sure the link from the email was copied correctly.");
}
} catch (fExpectedException $e) {
fMessaging::create('errorMessage', 'verify', $e->getMessage());
fMessaging::create('error', 'verify', "Your email could not be verified at this time, please be sure the link from the email was copied correctly.");
}
My problem is that when it runs, it is somehow setting the email token value to '' before running the if ($user->getEmailToken() == $emailToken) statement, so it always goes to false.
Actually, somehow not only is it setting that, it is also setting the email verified value to 1 and saving my user in the database. Am I doing something wrong with the way I have the try-catch exceptions laid out?

Related

How to override PHPMAILER exceptions?

i'm sending emails via phpmailer and i want to override the exceptions as when you send an email and that fail you can have the error message via :
echo json_encode"{$mail->ErrorInfo}";
but when the error is
"Empty body"
i would like to display something else.
Any solution ? Thanks
$new_msg = json_encode"{$mail->ErrorInfo}";
if ($new_msg == 'Empty body') {
throw new CustomException("You custom message ");
}
Wherever you are calling this function, catch the expectation there and show it to the user.
try {
if ($new_msg == 'Empty body') {
throw new CustomException("You custom message ");
}
} catch (CustomException $ex) {
//This is where you can have your own handling, exceptions that you want to handle separately
} catch (Exception $ex) {
// this part will handle general exceptions
// and show user some general error message
}
You can put your echo in a variable and then do an if check to display something else.
$new_msg = json_encode"{$mail->ErrorInfo}";
if ($new_msg == 'Empty body') {
echo 'You put here whatever you want';
} else {
echo json_encode"{$mail->ErrorInfo}";
}
Just catch the Exception and do something completely different!
try {
$something->thatWillThrowAnException();
} catch (Exception $e) {
// Do anything you want here!
}

PHP page not being displayed error 500

I'm trying to make a website by using PHP and when I run it, it comes back The sharedweb.uniwebsite.ac.uk page isn't working sharedweb.uniwebsite.ac.uk is currently unable to handle this request. 500 And when I click on the Details tab, I get Press the reload button to resubmit the data needed to load the page. Which I have done. The previous pages do work and I'm trying to work on the login page and when I go Register button, that's when I get the error
EDIT
The code that's causing the error is
<?php
// include function files for this application
require_once('bookmark_fns.php');
//create short variable names
$email=$_POST['email'];
$username=$_POST['username'];
$passwd=$_POST['passwd'];
$passwd2=$_POST['passwd2'];
// start session which may be needed later
// start it now because it must go before headers
session_start();
try {
// check forms filled in
if (!filled_out($_POST)) {
throw new Exception('You have not filled the form out correctly. Please go back and try again.');
}
// email address not valid
if (!valid_email($email)) {
throw new Exception('That is not a valid email address. Please go back and try again.');
}
// passwords not the same
if ($passwd != $passwd2) {
throw new Exception('The passwords you entered do not match. Please go back and try again.');
}
// check password length is ok
// ok if username truncates, but passwords will get
// munged if they are too long.
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z]{6,12}$/)', $passwd)) {
throw new Exception('Your password must be between 6 and 12 characters inclusive. Please go back and try again.');
}
// attempt to register
// this function can also throw an exception
register($username, $email, $passwd);
// register session variable
$_SESSION['valid_user'] = $username;
// provide link to members page
do_html_header('Registration successful');
echo "Welcome " $_POST["username"];
echo 'Your registration was successful. Go to the members page to start setting up your bookmarks!';
do_html_url('member.php', 'Go to members page');
// end page
do_html_footer();
}
catch (Exception $e) {
do_html_header('Warning:');
echo $e->getMessage();
do_html_footer();
exit;
}
?>
EDIT #2
It's still not working
There is an PHP error somewhere. To show the error add the following lines at the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
(remove them after fixing the error, to not expose any secrets later)
Possibility 2 would be to check your error.log, which will tell you why its not working too.

catching mailchimp php api errors

I am trying to create a subscribe method for my laravel app that uses the mailchimp api to subscribe a user to a given list. The method works fine when the email address is not already on the lsit. when it is already subscribed the mailchimp api throws the following error
Mailchimp_List_AlreadySubscribed blah#blah.co is already subscribed to
list Tc App Test List. Click here to update your profile.
with the following code being shown
public function castError($result) {
if($result['status'] !== 'error' || !$result['name']) throw new Mailchimp_Error('We received an unexpected error: ' . json_encode($result));
$class = (isset(self::$error_map[$result['name']])) ? self::$error_map[$result['name']] : 'Mailchimp_Error';
return new $class($result['error'], $result['code']);
}
I have attempted a try catch block to catch the error but it is still being returned to the browser, here is what I tried and were it says MailChimp_Error I tried with Exception as well.
public function subscribe($id, $email, $merge_vars)
{
try {
$this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (MailChimp_Error $e) {
$response = 'an error has occured';
}
return $response;
}
Ultimately I want to be able to run the method and then either return either a success message or a message describing the issue to the user. the 3 possible mailchimp method errors are Email_notexists, list_alreadysubscribed and list does not exist although tihs last one should not occur as I am providing the list in the source code.
edit 1; after being in touch with mailchimp api support they suggested this code but the error still gets returned to the browser in its entirety
try {
$results = $this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (Mailchimp_Error $e) {
if ($e->getMessage()) {
$error = 'Code:'.$e->getCode().': '.$e->getMessage();
}
}
echo $error;
You can do
try
{
$response = $this->mailchimp->lists->addListMember($list_id, [
"email_address" => $email,
"status" => "subscribed",
]);
}
catch (\EXCEPTION $e) {
return $e->getMessage();
}
The \EXCEPTION handles a sort of error for stripe
Subscribe is in a namespace Acme\Emails\Subscribe so catch(Mailchimp_Error $e) looks for Mailchimp_Error in this namespace.
Changing it to catch(\Mailchimp_Error $e) makes it look in the root namespace and then it works as intended

Bitcoin sendfrom not returning any errors

I am trying to validate bitcoin engine respond once executing with correct amount within the account balance and correct wallet I am getting transaction ID, but if I enter amount too much and fake wallet I am not receiving any error in return just a blank page with html, head and body elements. Is there is any debug mode or what I can do to receive any response?
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
I am using jsonRPCClient to connect with bitcoin engine.
however when I do that in console using RPC commands
I am getting this : Account has insufficient funds (code -6)
code for redirection
if ($message !== '') {
ob_start();
header("Location: mywallet.php?error=done");
die();
} else {
ob_start();
header("Location: mywallet.php?error=true");
die();
}
Update Yes correct I will more ob_start(); above, thing is that once trying (try,catch) event I am getting blank page upon SUCCESS (so not transaction ID like with normal way I am doing I am getting back transaction ID) upon FAIL I am getting Unable to connect to Bitcoin Server. What I just need sounds very simple, how do I verified that transaction is SUCCESSFUL or FAIL, SUCCESSFUL -> I got ID in return, FAIL -> I have got Error in return. SO I can divert users to right places on the page after form is submitted. Actualy I am doing is withdraw funds form, where user inserts amount and his wallet to get funds back from bitcoin account to his private account. Hope this will helps to understand.
UPDATE 2 I have changed construction for that and seems to is working very well, basically is looking for "Unable" word as transaction ID doesn't have that word and other exception I am getting is "Unable to connect to server..." Thank you for guiding me. Any feedback ?
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$e->getMessage();
}
// exit;
if (!strpos($e,'Unable') !== false){
header("Location: mywallet.php?error=done");
die();
} else {
header("Location: mywallet.php?error=true");
die();
}
What bitcoin php library are you using? Looks like maybe this one?
If that's the case, it doesn't return an error message, it throws BitCoinClientException
So you need something like
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
echo $e->getMessage();
}
Updating
The ob_start seems superfluous because you don't output anything before the header location. Unless you have output something before you've reached this point in which case you can't send a header. So you'd need to move the ob_start up towards the top of the script before any output.
Also you aren't sending message to the wallet.php script. Or are you done with it at that point?
RE: update 2
One thing I might add is the possibility of some other exception message occuring we haven't thought of yet that doesn't contain the "Unable." I'd do something more like:
$errorOccured = false;
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$errrorMessage = $e->getMessage();
$errorOccured = true;
}
if (!$errorOccured) {
...
}
else {
header("Location: mywallet.php?error=true&errormsg=" . $errorMessage);
...
}
This would require modifying mywallet.php to accept $errorMessage as an additional GET parameter so you can send it back to the user. Might be nice to additionally use another parameter for sending $message on success which would contain the transaction ID.

Show multiple catch messages in PHP

Is it possible to display all catches instead of only one? In the example below, what if both the username and email are wrong, can I output both instead of just one.
try {
// Code here
}
catch(WrongUsername $e) {
echo 'Your username is wrong.'
}
catch(WrongEmail $e) {
echo 'Your email is wrong too.'
}
You can probably loop thru all the validation rules and cathc all errors.
$errors = [];
foreach($rules as $rule){
try{
validate($input, $rule);
}catch(Exception $e){
$errors[] = $e->getMessage();
}
}
But then I don't see any reason to use try-catch at all.
This doesn't really make a lot of sense within PHP - it's dynamically, not fixed typed, and does not support overloading. In your example is 'WrongEmail' the class of the exception or the exception message? Is there a benefit to sub-classing exceptions?
If it's the message property of the exception, then change it to use something more informative...
try {
...
if (!preg_match($pattern, $username))
throw new Exception('Your username is wrong.');
...
} catch ($e) {
echo $e->message;
}
If you have a good reason for sub-classing your exceptions...
try {
...
} catch ($e) {
switch (get_class($e)) {
case 'WrongUsername':
echo 'Your username is wrong.';
break;
case 'WrongEmail':
echo 'Your email is wrong.'
break;
...
}
}
But exceptions are part of a flow control structure - when you throw an exception you change the flow of execution. A try{} block will never raise more than one exception. In terms of programming style it's debatable whether you should actually use exceptions at all for this kind of operation.
If you want to check a set of pre-conditions and deal with each failed requirement then don't use this construct.

Categories