I'm trying to customize error messages.
For handling errors i used "try/catch" block according to this Recurly documentation, like this for example:
try {
$account = Recurly_Account::get('my_account_id');
$subscription = new Recurly_Subscription();
$subscription->account = $account;
$subscription->plan_code = 'my_plan_code';
$subscription->coupon_code = 'my_coupon_code';
/* .. etc .. */
$subscription->create();
}
catch (Exception $e) {
$errorMsg = $e->getMessage();
print $errorMsg;
}
I wanted use code in catch block like this:
catch (Exception $e) {
$errorCode = $e->getCode();
print $myErrorMsg[$errorCode]; // array of my custom messages.
}
But getCode() method always returns zero for all possible errors.
My question for Recurly Team (or who there in this theme):
How i get error code for errors? Or please explain me how i can resolve this topic. Thanks!
If you look at the PHP Client on Github and you search for "throw new" which is what is done when an exception is thrown you'll see that they don't set the exception error code the second parameter of the exception constructor method.
Recurly PHP Client on Github: https://github.com/recurly/recurly-client-php/search?utf8=%E2%9C%93&q=throw+new
PHP Exception documentation: http://php.net/manual/en/language.exceptions.extending.php
Therefore, you'll either need to catch more exceptions based on their name
i.e.
catch (Recurly_NotFoundError $e) {
print 'Record could not be found';
}
OR
look at the exception message and compare it
catch (Exception $e) {
$errorMessage = $e->getMessage();
if($errorMessage=='Coupon is not redeemable.')
{
$myerrorCode=1;
}
//Add more else if, or case switch statement to handle the various errors you want to handle
print $myErrorMsg[$myerrorCode]; // array of my custom messages.
}
Related
I'm trying to do a very basic exception try catch, but it doesn't catch.
$id =0;
try {
$question = $this->model->find($id); // will not find anything since $id = 0
$question->delete(); // throw an exception
return true;
} catch (\Exception $e) {
dd ('hello'); // should end up here, but no?!?!?
} catch (FatalThrowableError $f) {
echo ("fatal"); // or here... but no.
}
but the catch doesn't "catch". I get an Fatal error in the browser saying that delete was called on a null object. But that's exactly what I was trying to do: do a delete on a null object (id = 0 is not in the DB), to test the exception.
I have tried
use Symfony\Component\Debug\Exception;
use Symfony\Component\Debug\Exception\FatalThrowableError;
or simply
Exception;
FatalThrowableError;
Also, having the \Exception $e or Exception $e (with or without ) doesn't change anything.
Note that if I add a line like $foo = 4/0 I get into the Exception section (dd (hello)).
in .env APP_DEBUG=true, APP_LOG_LEVEL=debug
I'm on Laravel 5.5 using PHP 7.0.10 on windows 7.
http://php.net/manual/en/language.errors.php7.php
As the Error hierarchy does not inherit from Exception, code that uses
catch (Exception $e) { ... } blocks to handle uncaught exceptions in
PHP 5 will find that these Errors are not caught by these blocks.
Either a catch (Error $e) { ... } block or a set_exception_handler()
handler is required.
You can, additionally, catch (\Throwable $e) {} to account for both Error and Exception types.
I am using Stripe for a german website, I could translate the JS (stripeResponseHandler) error messages for the form following this post but not the exception of validation ($e->getMessage()).
I get the exception error in english, how can I translate it?
My PHP :
try {
require_once('Stripe/init.php');
\Stripe\Stripe::setApiKey("myKey"); //Secret Key
$token = $_POST['stripeToken'];
$coupon = \Stripe\Coupon::retrieve($_POST['couponId']);
$charge = \Stripe\Charge::create(array(...)
} catch (Exception $e) {
echo $e->getMessage();
}
The error messages returned by the API are in English -- at this time, Stripe does not have support for localized API error messages.
You can do what's described in the SO answer you linked to provide your own translations via error handling. E.g. you could do something like:
try {
$charge = \Stripe\Charge::create(...);
} catch(\Stripe\Error\Card $e) {
$body = $e->getJsonBody();
$err = $body['error'];
switch ($err['code']) {
case 'card_declined':
// use your own "card declined" error message
break;
case 'invalid_number':
// use your own "invalid number" error message
break;
// etc.
}
} catch (\Stripe\Error\Base $e) {
// another Stripe error happened, use a generic "error with our payment processor" message
} catch (Exception $e) {
// something else happened, unrelated to Stripe
}
I have a custom error handlers:
set_error_handler('API_Error_Handler');
register_shutdown_function('Fatal_Error_Handler'); // This one calls API_Error_Handler eventually
In the following example, both catch{} section AND API_Error_Handler are executed.
try{
// Exception raised here
} catch(Exception $e){
// No error reporting needed, do something else
}
I want ONLY catch{} to execute. How do I do that? Maybe determine within API_Error_Handler whether exception is already caught by try-catch? Or are there other approaches available?
Example code:
set_error_handler(function() {
echo "Error is handled by custom error handler. <br>";
});
try{
new SoapClient('http://bad.address/wsdl');
} catch(Exception $e){
echo "Error is caught. <br>";
}
I think the best way will be to create an Exception class by your self that extends Exception:
class MyCustomException extends \Exception {}
and throw this where you need it. Then change
} catch (Exception $e)
to
} catch (MyCustomException $e)
and you should only get your custom exception catched
I wonder if it's posible to get all the exceptions throwed.
public function test()
{
$arrayExceptions = array();
try {
throw new Exception('Division by zero.');
throw new Exception('This will never get throwed');
}
catch (Exception $e)
{
$arrayExceptions[] = $e;
}
}
I have a huge try catch block but i want to know all the errors, not only the first throwed. Is this possible with maybe more than one try or something like that or i am doing it wrong?
Thank you
You wrote it yourself: "This will never get throwed" [sic].
Because the exception will never get thrown, you cannot catch it. There only is one exception because after one exception is thrown, the whole block is abandoned and no further code in it is executed. Hence no second exception.
Maybe this was what the OP was actually asking for. If the function is not atomic and allows for some level of fault tolerance, then you can know all the errors that occurred afterwards instead of die()ing if you do something like this:
public function test()
{
$arrayExceptions = array();
try {
//action 1 throws an exception, as simulated below
throw new Exception('Division by zero.');
}
catch (Exception $e)
{
//handle action 1 's error using a default or fallback value
$arrayExceptions[] = $e;
}
try {
//action 2 throws another exception, as simulated below
throw new Exception('Value is not 42!');
}
catch (Exception $e)
{
//handle action 2 's error using a default or fallback value
$arrayExceptions[] = $e;
}
echo 'Task ended. Errors: '; // all the occurred exceptions are in the array
(count($arrayExceptions)!=0) ? print_r($arrayExceptions) : echo 'no error.';
}
I been searching for this and I just seem to run into the same articles, in this code:
try
{
//some code
}
catch(Exception $e){
throw $e;
}
Where does $e gets stored or how the webmaster see it? Should I look for a special function?
An Exception object (in this case, $e) thrown from inside a catch{} block will be caught by the next highest try{} catch{} block.
Here's a silly example:
try {
try {
throw new Exception("This is thrown from the inner exception handler.");
}catch(Exception $e) {
throw $e;
}
}catch(Exception $e) {
die("I'm the outer exception handler (" . $e->getMessage() . ")<br />");
}
The output of the above is
I'm the outer exception handler (This is thrown from the inner exception handler.)
One nice thing is that Exception implements __toString() and outputs a call stack trace.
So sometimes in low-level Exceptions that I know I'm gonna want to see how I got to, in the catch() I simply do
error_log($e);
$e is an instance of Exception or any other class that extended from Exception. Those objects have some specific attributes and methods in common (inherited from the Exception class) you can use. See the chapter about exceptions and the Exception member list for more details.
I'm assuming your using some sort of third party code/library with this code in it that is throwing the exception into your code. You simply have to be ready for an exception to be thrown to catch it, then you can log it/display it however you want.
try {
$Library->procedure();
catch(Exception $e) {
echo $e->getMessage(); //would echo the exception message.
}
For more information read the PHP manual's entry on Exceptions.
The lines:
catch(Exception $e){
throw $e;
}
Don\t make sense. When you catch an Exception you're suppose to do something with the exception like:
catch(Exception $e){
error_log($e->getMessage());
die('An error has occurred');
}
But in your case the Exception is thrown directly to an outer try-block which would already happen.
If you change your code to:
//some code
Would create the exact same behaviour.