I am making a bitcoin faucet using the coinbase api, and was looking to validate the address. I looked online to see if there are any good scripts, and couldnt find any so I decided to test and see if it was already built in the API, and it was! The the thing is that instead of just saying that is not a valid address it php displays a LONG error...
Fatal error: Uncaught exception 'Coinbase_ApiException' with message 'Please enter a valid email or bitcoin address' in C:\xampp\htdocs\nahtnam\lib\Coinbase\Rpc.php:84 Stack trace: #0 C:\xampp\htdocs\nahtnam\lib\Coinbase\Coinbase.php(39): Coinbase_Rpc->request('POST', 'transactions/se...', Array) #1 C:\xampp\htdocs\nahtnam\lib\Coinbase\Coinbase.php(118): Coinbase->post('transactions/se...', Array) #2 C:\xampp\htdocs\nahtnam\faucet.php(54): Coinbase->sendMoney('17FSKMPAyXGR7EQ...', '0.00000555', 'this is a test') #3 {main} thrown in C:\xampp\htdocs\nahtnam\lib\Coinbase\Rpc.php on line 84
Is ther any way i can just set $address_error to "Please enter a valid Address" (not email) if this occurs and also not display the error? Thanks!
Expanding on aliasm2k's answer, you probably want to do it more like this:
EDIT: Changed answer slightly based on comments discussion
I think I was a bit unclear on what you were asking for in the comments.
try {
$result = $Coinbase->sendMoney($bitcoinaddress, '0.00000555', 'this is a test');
catch(Exception $e) {
echo $e->getMessage();
exit; //optional but you probably want to quit here and show the user
//the original form along with the error message to fix
}
This is just going to echo "Please enter a valid email or bitcoin address." You wont get all of that other info because you are catching the exception and just displaying the message.
Possible error messages are listed here.
Also, if I can give you a slightly off-topic hint:
If you want to find info about a particular address that has been used, try the blockchain block explorer api.
And to simply check if an address is valid, you need to calculate that in your code or find a library function to do so. There's no master-list of addresses that an api would have. The last 4 bytes of the address are a double-sha-256 checksum of the preceding characters. That's sort-of an imprecise description I'm giving you, by the way, but check here for a working php example
Use try and catch.
try {
if(/*invalid address check returns true*/)
throw 'Invalid address';
} catch(Exception $e) {
echo 'Exception: ' . $e->getMessage();
}
Related
The problem
I created a constraint in my SQL database to prevent duplicate entries. The initial laravel form submission works fine. I get back the correct message. When I try to throw a duplicate entry, the app, as expected, throws an error.
This is my Controller. A successful form submission does throw the correct error:
$contact->save();
return redirect('contactus.php')->with('status', 'We received your message. We will get back to you soon.');
return back()->withErrors(['Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.']);
Question
How do I display that error on the HTML screen? Instead of having the page display the following?
Basically the contact form submits information into the database using laravel. When successful, it displays a success message by redirecting it. When not successful, (because of a SQL Unique constraint blocking duplicate entries) so far I've managed to make it throw a SQL error.
How do I display a custom message, like "post not successful, duplicate entry" in that case?
You can do it by using try catch and query exception:
try {
$contact->save();
return redirect('contactus.php')->with('status', 'We received your message. We will get back to you soon.');
} catch(\Illuminate\Database\QueryException $e){
$errorCode = $e->errorInfo[1];
if($errorCode == '1062'){
return back()->with('error', 'Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.');
}
else{
return back()->with('error', $e->getMessage());
}
}
or another way you can find/check the data first, if already exist just send the error. example:
$contact = Contact::where('email',$request->email)->first();
if($contact)
{
return back()->with('error', 'Your message may be a duplicate. Did you refresh the page? We blocked that submission. If you feel this was in error, e-mail us or call us.');
}
dont forget to get the error on the form view using like below:
<script>
#if(session()->has('error'))
alert('{{session()->get('error')}}')
#endif
</script>
First time doing this. I am having a tough time trying to complete this. Three days on this now. I transitioned the php Twilio/sdk over to Laravel and have successfully sent a text with Twilio's api to my phone. I am now figuring out how to receive the reply text.
(I tried the laravel packages for this and they only send the text, not receive the reply)
I am getting an error on my code.
Undefined index: From
If I move the header to my view I get a whoops error.
I also tried replacing the REQUEST with
$name = in_array(Input::get('name'), $people) ? Input::get('name') : 'default';
Here is my receiving function
public function getReceiveSMS() {
// make an associative array of senders we know, indexed by phone number
$people = array(
"1111111111"=>"Curious George",
"1111111111"=>"Boots",
"1111111111"=>"Virgil",
"1111111111"=>"Stephen",
);
// if the sender is known, then greet them by name
// otherwise, consider them just another monkey
if(!$name = $people[$_REQUEST['From']]) {
$name = "Monkey";
}
// now greet the sender
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
return View::make('account.sms.receive-sms');
}
}
Here is my view
#extends('layout.main')
#section('content')
<Response>
<Message><?php echo $name ?>, thanks for the message!</Message>
</Response>
#stop
I don't know about Twilio's API, but it seems the error is just basic PHP, and you're being held back by the fact that Laravel is far less lenient than regular PHP, meaning undefined variables and indexes will halt processing just like a fatal error would.
If in fact the sender can be unknown, and when that does happen the From index won't ever be set, the following should prevent your code from triggering a Notice:
// if the sender is known, then greet them by name
// otherwise, consider them just another monkey
if(!isset($_REQUEST['From']) || !$name = $people[$_REQUEST['From']]) {
$name = "Monkey";
}
As for your malformed XML, try this instead of a simple View::make():
return Response::view('account.sms.receive-sms', compact('name'))->header('Content-Type', 'text/xml');
So basically I want to be able to somehow do a few if statements to check what exception is being thrown in order for me to echo out some appropriate error messages, e.g.
IF exception is a duplicate record exception in MySQL
THEN echo "User Already exists";
So below I have caught the exception and it prints the default exception error message however this doesn't look good for the user so I want to check what the error is, then print out my own appropriate error message that users would be able to recognise... such as 'User Already Exists'.
try{
$query = "INSERT INTO user VALUES ('', 0, $safe_email, '$hashed_password')";
$result = $db->query($query);
echo '<script type="text/javascript"> alert(\'You have successfully registered.\n A confirmation email has been sent to you.\'); window.location = \'index.php\'; </script>';
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
You should check if the user exists in a "non exceptional" way first, since it's impossible, or at least pretty tricky, to get relevant and consistent information out of the MySQL exception.
For example, if you suddenly decide to add an id field to your table and set it as a primary key, your algorithm would break. If you manage to parse the MySQL error by identifying the error number or something, you're also very tightly coupled to your database and it might be tricky to switch to MariaDB or Postgres or whatever...
Leave the exceptions for the truly exceptional cases, such as
User A and B tries to sign up as "Adam" at roughly the same time
Your server checks UserModel->usernameExists("Adam") of something like that, it returns false in both cases.
Your registration controller continues the registration process for both users, user A gets registered but user B receives an exception, which is actually exceptional and due to this stupid race condition).
If user A registers two weeks before user B tries to register, however, UserModel->usernameExists("Adam") would just return true for user B, and you could show a nice error - or just show that the username is taken, in the registration form.
I am trying to send email invitations with CakePHP (2.3.6) where a User enters a comma separated list of email addresses into an input field.
Currently, I can send emails without an issue as long as there is no invalid email address. However, I tried adding a Try/Catch to catch errors if there was a bad email, but my code is never hitting the catch.
Here is what I have
try {
if($Email->send()) {
$this->Session->setFlash(__('Email successfully sent'), 'flash/success');
} else {
$this->Session->setFlash(__('Could not invite guests. Please, try again.'), 'flash/error');
$this->redirect($this->referer());
}
} catch(Exception $e) {
$this->Session->setFlash(__('Could not invite guests. Probably a bad email. Please, try again.'), 'flash/error');
$this->redirect($this->referer());
}
$this->redirect($this->referer());
When I enter an invalid email with debugging on, I get the following error:
Invalid email: "foo"
Error: An Internal Error Has Occurred.
And when debugging is off:
An Internal Error Has Occurred.
I assumed there is something wrong with my Try / Catch, but it looks right to me. Is there some other method I should be going through to catch CakePHP errors?
Thanks in advance!!
Invalid email addresses cause the exception to be thrown right away when they are set. This occurs before the send method is called, so it is not reaching the try block you posted.
This is from a component I have written that handles sending several different emails for our system here. I have wrapped each address setting in a try block so the offending address can be more easily tracked down, but if you did not want that much detail you could wrap all of them in a single block. You can examine the message from the exception with the getMessage method to see the offending address string. This works for me with Cake 2.3:
$email = new CakeEmail();
//...
// set to for email
try
{
$email->to($recipient);
}
catch(SocketException $e)
{
$result['problem'] = 'Recipient Address';
$result['message'] = $e->getMessage();
return $result;
}
// set cc for email - not required
try
{
if($cclist != '') $email->cc(preg_split('/, */', $cclist));
}
catch(SocketException $e)
{
$result['problem'] = 'CC List';
$result['message'] = $e->getMessage();
return $result;
}
Check where exactly the exception causing this error is thrown, it is most likely not in the try block you've posted, but in one of the CakeEmail methods (from, sender, replyTo, etc...) that validates the address.
That being said, you should probably either wrap the single CakeEmail method calls into try catch blocks (in case you want to respond with proper error messages depending on which value exactly is wrong), or maybe use a single one that wraps all operations and output a generic error message.
Also note that CakeEmail::send() returns an array (containing header and message data), not a boolean, determining whether an E-Mail was send successfully must be done using try...catch, ie when no exception is being thrown, then the E-Mail was probably sent successfully.
Unfortunately the Cookbook is missing some proper examples. Here's some untested example code that should illustrate how it might work:
$Email = new CakeEmail();
try
{
$Email->from($from);
$Email->to($to);
// etc...
try
{
$Email->send();
$this->Session->setFlash(__('Email successfully sent'), 'flash/success');
}
catch(SocketException $e)
{
$this->Session->setFlash(__('Could not invite guests. Please, try again.'), 'flash/error');
}
}
catch(SocketException $e)
{
$this->Session->setFlash(__('Bad input'), 'flash/error');
}
$this->redirect($this->referer());
Im using a php web form to insert product registrations into a .NET published web service. My insertXmlData function works, but I'm having trouble with error handling. When I attempted to insert a record with an already existing serial number Im getting this returned:
ERROR-5002 - Unique serial number must not be blank System.Exception
I tried this:
try
{
$xmlData = insertXmlData($url, $xml);
}
catch (Exception $e)
{
echo ("Triggered");
throw new Exception( 'There was an error...', 0, $e);
}
But the catch clause doesn't even trigger. Is it a .NET to php thing or is my syntax incorrect? What's my best option for handling errors in this situation?