How handling error of JSON decode by try and catch - php

I am unable to handle JSON decode errors. Here is my code:
try {
$jsonData = file_get_contents($filePath) . ']';
$jsonObj = json_decode($jsonData, true);
}
catch (Exception $e) {
echo '{"result":"FALSE","message":"Caught exception: ' . $e->getMessage() . ' ~' . $filePath . '"}';
}
I am a new PHP programmer. Sorry, if something is wrong.

Another way to handle json decode error:-
if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
echo "json data is incorrect";
}

Since PHP 7.3 one can use the JSON_THROW_ON_ERROR constant.
try {
$jsonObj = json_decode($jsonData, $associative=true, $depth=512, JSON_THROW_ON_ERROR);
} catch (Exception $e) {
// handle exception
}
More: https://www.php.net/manual/de/function.json-decode.php#refsect1-function.json-decode-changelog

May be you can try, validating json_decode
try {
$jsonData = file_get_contents($filePath) . ']';
$jsonObj = json_decode($jsonData, true);
if (is_null($jsonObj)) {
throw ('Error');
}
} catch (Exception $e) {
echo '{"result":"FALSE","message":"Caught exception: ' .
$e->getMessage() . ' ~' . $filePath . '"}';
}
Read this too

json_decode returns null when a error occurs, like no valid json or exceeded depth size. So basically you just check with if whether the jsondata you obtained is null or not. If it is, use json_last_error to see what went wrong, if not then continue with the script.
$json_data = json_decode($source, true);
if($json_data == null){
echo json_last_error() . "<br>";
echo $source; // good to check what the source was, to see where it went wrong
}else{
//continue with script
}
Something like that should work.

Related

php rest API POST request returning null

I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??

What is the proper way to capture a "Response too large to return error" in Google BigQuery API for PHP?

In the Google BigQuery web interface, if I run a query that returns a response that is too large, I receive the message:
Error: Response too large to return. Consider setting allowLargeResults to true in your job configuration.
How can I capture this error message in the Google BigQuery API interface when running a query that does not have allowLargeResults set in the job configuration?
In respective BigQuery API - Jobs: get this info is in status.errorResult
Respectivelly in
reason property: responseTooLarge
message property: Response too large to return. Consider setting allowLargeResults to true in your job configuration. For more details, ...
You can also check status.errors for more details for all errors encountered during job execution
We use this fragment to handle errors, and it helped out:
We have also when we place the job, and later when we check the status of the job in a loop, as that error popups up when the job is done.
try {
try {
$job = $bq->jobs->insert(PROJECT_ID, $job);
} catch (Google_IO_Exception $e) {
$this->e('Exception: ' . $e->getMessage(), 'red');
$this->e('Strace: ' . $e->getTraceAsString());
if ($e->getMessage() == 'SSL connect error') {
$this->clearTokenFile();
$this->releaseJob();
}
return false;
}
$status = new Google_Service_Bigquery_JobStatus();
$status = $job->getStatus();
if (0 != $status->count()) {
$err_res = $status->getErrorResult();
$this->e($err_res->getMessage(), 'red');
return false;
}
} catch (Google_Service_Exception $e) {
$this->e('Exception: ' . $e->getMessage(), 'red');
return false;
}
on and insertAll we have, here pay attention to the reason field:
try {
$resp = new Google_Service_Bigquery_TableDataInsertAllResponse();
$resp = $bq->tabledata->insertAll($project_id, $dataset_id, static::tableId(), $request);
$errors = new Google_Service_Bigquery_TableDataInsertAllResponseInsertErrors();
$errors = #$resp->getInsertErrors();
if (!empty($errors)) {
$error_msg = "\r\nRequest Headers: \r\n" . json_encode($client->request->getRequestHeaders()) . "\r\nResponse Headers: \r\n" . json_encode($client->request->getResponseHeaders()) . "\r\nRequest Body:\r\n" . $client->request->getPostBody() . "\r\nResponse Body:\r\n" . $client->request->getResponseBody() . "\r\n";
if (is_array($errors)) {
foreach ($errors as $eP) {
$arr = $eP->getErrors();
$line = $eP->getIndex();
if (is_array($arr)) {
foreach ($arr as $e) {
switch ($e->getReason()) {
case "stopped":
break;
case "timeout":
$failed_lines[] = $line;
$last_reason = $e->getReason();
$error_msg.= sprintf("Timeout on line %s, reason: %s, msg: %s\r\n", $line, $e->getReason(), $e->getMessage());
break;
default:
$error_msg.= sprintf("Error on line %s, reason: %s, msg: %s\r\n", $line, $e->getReason(), $e->getMessage());
break;
}
}
} else {
$error_msg.= json_encode($arr) . "\r\n";
}
}
$this->setErrorMessage($error_msg);
} else {
$this->setErrorMessage($errors);
}
//print_r($errors);
//exit;
$success = false;
}
return $ret;
} catch (Google_Service_Exception $e) {
$this->setErrors($e->getErrors())->setErrorMessage($e->getMessage());
throw $e;
}
Answering my own question: Here's a summary of what resolved it for me. In summary, I couldn't get it to throw an error for Synchronous Queries, but was able to get it to throw for Asynchronous Queries.
Here is a sample query with a response too large to return:
$query = "SELECT * FROM [publicdata:samples.github_timeline] LIMIT 1000000;"
Synchronous Queries
Running a synchronous query with jobs.query:
try {
$query_request = new Google_Service_Bigquery_QueryRequest();
$query_request->setQuery($query);
$res = $this->gbq_service->jobs->query($this->_project_id, $query_request);
return $res;
} catch (Exception $e){
echo $e->getMessage());
}
The response I receive is:
{
"cacheHit": null,
"jobComplete": false,
"kind": "bigquery#queryResponse",
"pageToken": null,
"totalBytesProcessed": null,
"totalRows": null
}
So in this case, I still don't receive the desired "response too large to return".
Asynchronous Queries
If I run the job as an asynchronous query, the job status is eventually set to DONE, and on checking the results, an error is thrown with message:
{
"error": "Error calling GET https://www.googleapis.com/bigquery/v2/projects/.../queries/job_2VICoK6yX0YMM_zRkJ10hT9mom8?timeoutMs=1000000&maxResults=100: (403) Response too large to return. Consider setting allowLargeResults to true in your job configuration. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors",
}
Telling me that I need to save the results as a table and set allowLargeResults to true.
So, the short answer is- run your queries as asynchronous queries.
Update
I've contacted google and they mentioned it may be a bug in the php api. They have said they will forward it to the php gbq API people.

Catching Stripe errors with Try/Catch PHP method

During my testing of STRIPE in a website, I built the code like this:
try {
$charge = Stripe_Charge::create(array(
"amount" => $clientPriceStripe, // amount in cents
"currency" => "usd",
"customer" => $customer->id,
"description" => $description));
$success = 1;
$paymentProcessor="Credit card (www.stripe.com)";
}
catch (Stripe_InvalidRequestError $a) {
// Since it's a decline, Stripe_CardError will be caught
$error3 = $a->getMessage();
}
catch (Stripe_Error $e) {
// Since it's a decline, Stripe_CardError will be caught
$error2 = $e->getMessage();
$error = 1;
}
if ($success!=1)
{
$_SESSION['error3'] = $error3;
$_SESSION['error2'] = $error2;
header('Location: checkout.php');
exit();
}
The problem is that sometimes there is an error with the card (not catched by the "catch" arguments I have there) and the "try" fails and the page immediately posts the error in the screen instead of going into the "if" and redirecting back to checkout.php.
How should I structure my error handling so I get the error and immediately redirect back to checkout.php and display the error there?
Thanks!
Error thrown:
Fatal error: Uncaught exception 'Stripe_CardError' with message 'Your card was declined.' in ............
/lib/Stripe/ApiRequestor.php on line 92
If you're using the Stripe PHP libraries and they have been namespaced (such as when they're installed via Composer) you can catch all Stripe exceptions with:
<?php
try {
// Use a Stripe PHP library method that may throw an exception....
\Stripe\Customer::create($args);
} catch (\Stripe\Error\Base $e) {
// Code to do something with the $e exception object when an error occurs
echo($e->getMessage());
} catch (Exception $e) {
// Catch any other non-Stripe exceptions
}
I think there is more than these exceptions (Stripe_InvalidRequestError and Stripe_Error) to catch.
The code below is from Stripe's web site. Probably, these additional exceptions, which you didn't consider, occurs and your code fails sometimes.
try {
// Use Stripe's bindings...
} catch(Stripe_CardError $e) {
// Since it's a decline, Stripe_CardError will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
EDIT:
try {
$charge = Stripe_Charge::create(array(
"amount" => $clientPriceStripe, // amount in cents
"currency" => "usd",
"customer" => $customer->id,
"description" => $description));
$success = 1;
$paymentProcessor="Credit card (www.stripe.com)";
} catch(Stripe_CardError $e) {
$error1 = $e->getMessage();
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
$error2 = $e->getMessage();
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
$error3 = $e->getMessage();
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
$error4 = $e->getMessage();
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error5 = $e->getMessage();
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error6 = $e->getMessage();
}
if ($success!=1)
{
$_SESSION['error1'] = $error1;
$_SESSION['error2'] = $error2;
$_SESSION['error3'] = $error3;
$_SESSION['error4'] = $error4;
$_SESSION['error5'] = $error5;
$_SESSION['error6'] = $error6;
header('Location: checkout.php');
exit();
}
Now, you will catch all possible exceptions and you can display error message as you wish. And also $error6 is for unrelated exceptions.
This is an update to another answer, but the docs have changed very slightly so I had success using the following method:
try {
// Use Stripe's library to make requests...
} catch(\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '\n';
echo 'Type is:' . $e->getError()->type . '\n';
echo 'Code is:' . $e->getError()->code . '\n';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '\n';
echo 'Message is:' . $e->getError()->message . '\n';
} catch (\Stripe\Exception\RateLimitException $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Exception\AuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Exception\ApiConnectionException $e) {
// Network communication with Stripe failed
} catch (\Stripe\Exception\ApiErrorException $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
You can find the source of this in the Stripe docs right here:
https://stripe.com/docs/api/errors/handling?lang=php
I may be late to this question, but I ran into the same issue and found this.
You just need to use "Stripe_Error" class.
use Stripe_Error;
After declaring that, I was able to catch errors successfully.
This is how Stripe catches errors: Documentation.
try {
// make Stripe API calls
} catch(\Stripe\Exception\ApiErrorException $e) {
$return_array = [
"status" => $e->getHttpStatus(),
"type" => $e->getError()->type,
"code" => $e->getError()->code,
"param" => $e->getError()->param,
"message" => $e->getError()->message,
];
$return_str = json_encode($return_array);
http_response_code($e->getHttpStatus());
echo $return_str;
}
You can then catch the error in ajax with the following code:
$(document).ajaxError(function ajaxError(event, jqXHR, ajaxSettings, thrownError) {
try {
var url = ajaxSettings.url;
var http_status_code = jqXHR.status;
var response = jqXHR.responseText;
var message = "";
if (isJson(response)) { // see here for function: https://stackoverflow.com/a/32278428/4056146
message = " " + (JSON.parse(response)).message;
}
var error_str = "";
// 1. handle HTTP status code
switch (http_status_code) {
case 0: {
error_str = "No Connection. Cannot connect to " + new URL(url).hostname + ".";
break;
} // No Connection
case 400: {
error_str = "Bad Request." + message + " Please see help.";
break;
} // Bad Request
case 401: {
error_str = "Unauthorized." + message + " Please see help.";
break;
} // Unauthorized
case 402: {
error_str = "Request Failed." + message;
break;
} // Request Failed
case 404: {
error_str = "Not Found." + message + " Please see help.";
break;
} // Not Found
case 405: {
error_str = "Method Not Allowed." + message + " Please see help.";
break;
} // Method Not Allowed
case 409: {
error_str = "Conflict." + message + " Please see help.";
break;
} // Conflict
case 429: {
error_str = "Too Many Requests." + message + " Please try again later.";
break;
} // Too Many Requests
case 500: {
error_str = "Internal Server Error." + message + " Please see help.";
break;
} // Internal Server Error
case 502: {
error_str = "Bad Gateway." + message + " Please see help.";
break;
} // Bad Gateway
case 503: {
error_str = "Service Unavailable." + message + " Please see help.";
break;
} // Service Unavailable
case 504: {
error_str = "Gateway Timeout." + message + " Please see help.";
break;
} // Gateway Timeout
default: {
console.error(loc + "http_status_code unhandled >> http_status_code = " + http_status_code);
error_str = "Unknown Error." + message + " Please see help.";
break;
}
}
// 2. show popup
alert(error_str);
console.error(arguments.callee.name + " >> http_status_code = " + http_status_code.toString() + "; thrownError = " + thrownError + "; URL = " + url + "; Response = " + response);
}
catch (e) {
console.error(arguments.callee.name + " >> ERROR >> " + e.toString());
alert("Internal Error. Please see help.");
}
});
I think all you really need to check is the base error class of Stripe and the exception if it's unrelated to Stripe. Here's how I do it.
/**
* Config.
*/
require_once( dirname( __FILE__ ) . '/config.php' );
// Hit Stripe API.
try {
// Register a Customer.
$customer = \Stripe\Customer::create(array(
'email' => 'AA#TESTING.com',
'source' => $token,
'metadata' => array( // Note: You can specify up to 20 keys, with key names up to 40 characters long and values up to 500 characters long.
'NAME' => 'AA',
'EMAIL' => 'a#a.c.o',
'ORDER DETAILS' => $order_details,
)
));
// Charge a customer.
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => 5000, // In cents.
'currency' => 'usd'
));
// If there is an error from Stripe.
} catch ( Stripe\Error\Base $e ) {
// Code to do something with the $e exception object when an error occurs.
echo $e->getMessage();
// DEBUG.
$body = $e->getJsonBody();
$err = $body['error'];
echo '<br> ——— <br>';
echo '<br>THE ERROR DEFINED — <br>';
echo '— Status is: ' . $e->getHttpStatus() . '<br>';
echo '— Message is: ' . $err['message'] . '<br>';
echo '— Type is: ' . $err['type'] . '<br>';
echo '— Param is: ' . $err['param'] . '<br>';
echo '— Code is: ' . $err['code'] . '<br>';
echo '<br> ——— <br>';
// Catch any other non-Stripe exceptions.
} catch ( Exception $e ) {
$body = $e->getJsonBody();
$err = $body['error'];
echo '<br> ——— <br>';
echo '<br>THE ERROR DEFINED — <br>';
echo '— Status is: ' . $e->getHttpStatus() . '<br>';
echo '— Message is: ' . $err['message'] . '<br>';
echo '— Type is: ' . $err['type'] . '<br>';
echo '— Param is: ' . $err['param'] . '<br>';
echo '— Code is: ' . $err['code'] . '<br>';
echo '<br> ——— <br>';
}
How to get error message if your provided token is invalid. It break and show some exception in laravel. so i used stripe exception by using try and catch. It will work fine. try this code.You can show your own custom message instead of stripe message.
try{
\Stripe\Stripe::setApiKey ("your stripe secret key");
$charge = \Stripe\Charge::create ( array (
"amount" => 100,
"currency" => "USD",
"source" => 'sdf', // obtained with Stripe.js
"description" => "Test payment."
) );
$order_information = array(
'paid'=>'true',
'transaction_id'=>$charge->id,
'type'=>$charge->outcome->type,
'balance_transaction'=>$charge->balance_transaction,
'status'=>$charge->status,
'currency'=>$charge->currency,
'amount'=>$charge->amount,
'created'=>date('d M,Y', $charge->created),
'dispute'=>$charge->dispute,
'customer'=>$charge->customer,
'address_zip'=>$charge->source->address_zip,
'seller_message'=>$charge->outcome->seller_message,
'network_status'=>$charge->outcome->network_status,
'expirationMonth'=>$charge->outcome->type
);
$result['status'] = 1;
$result['message'] = 'success';
$result['transactions'] = $order_information;
}
catch(\Stripe\Exception\InvalidRequestException $e){
$result['message'] = $e->getMessage();
$result['status'] = 0;
}
Here is a functional demo of the try / catch with all the possible errors, just add your own functionality in each catch
try {
// Use Stripe's library to make requests...
$charge = \Stripe\Charge::create([
'amount' => $amount,
'currency' => "usd",
'description' => $description,
"receipt_email" => $mail,
]);
} catch(\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '\n';
echo 'Type is:' . $e->getError()->type . '\n';
echo 'Code is:' . $e->getError()->code . '\n';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '\n';
echo 'Message is:' . $e->getError()->message . '\n';
} catch (\Stripe\Exception\RateLimitException $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Exception\AuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Exception\ApiConnectionException $e) {
// Network communication with Stripe failed
} catch (\Stripe\Exception\ApiErrorException $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
You can get the official code from here

Retrieve Error Message with array

I have using a version of GoCardless's API in PHP to process payments on my website. However when their API returns an error I would like to display the user more effective errors.
I have got half way there but I was wondering if there is anyway I could do the following:
If I have the following error:
Array ( [error] => Array ( [0] => The resource has already been confirmed ) )
Is there anyway to extract just the The resource has already been confirmed part with PHP?
My Code:
try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
print '<h2>Payment Error</h2>
<p>Server Returned : <code>' . $e->getMessage() . '</code></p>';
}
Thanks.
UPDATE 1:
Code that triggers the exception:
$http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_response_code < 200 || $http_response_code > 300) {
// Create a string
$message = print_r(json_decode($result, true), true);
// Throw an exception with the error message
throw new GoCardless_ApiException($message, $http_response_code);
}
UPDATE 2 :-> print_r($e->getMessage()) Output:
Array ( [error] => Array ( [0] => The resource has already been confirmed ) )
The method $e->getMessage() appears to return an array with an index 'error' wich is an array again that contains the message text. If you ask me this is bad API design
However you can access the message text like this:
try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
$message = $e->getMessage();
$error = $message['error'];
print '<h2>Payment Error</h2>
<p>Server Returned : <code><' . $error[0] . "</code></p>";
}
If you look into the GoCardless_ApiException class code you'll see that there's a getResponse() method that you could use to access the error element of the response array...
$try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
$response = $e->getResponse();
print '<h2>Payment Error</h2>
<p>Server Returned : <code>' . $response['error'][0] . "</code></p>";
}
I discovered the problem, the output from $e->getMessage() was a plain string, NOT an array.
So I edited the Request.php file to the following:
$http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_response_code < 200 || $http_response_code > 300) {
// Create a string <<-- THE PROBLEM -->>
// $message = print_r(json_decode($result, true), true);
$message_test = json_decode($result, true);
// Throw an exception with the error message
// OLD - throw new GoCardless_ApiException($message, $http_response_code);
throw new GoCardless_ApiException($message_test[error][0], $http_response_code);
}
and then my php file :
try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
$message = $e->getMessage();
print '<h2>Payment Error</h2>
<p>Server Returned : <code>' . $message . "</code></p>";
}
and the page outputs:
Payment Error
Server Returned : The resource has already been confirmed

PHP If file_get_contents fails, do this instead

I have a function to translate the current text string using the Free Bing translator API. I just want to make sure if anything fails or something happens with the Application ID or I go over on requests, I don't want a big error to show.
The code I have right now is:
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$translate = simplexml_load_string($translate_feed);
return $translate[0];
What I want to happen is if anything fails, so if I add in another character to the URL to make it invalid then I want it to just return $text so at least something shows.
Thanks!
Have you tried failing it on purpose to see what happens?
If it's an exception, just catch it and handle it...
try{
//enter code to catch
}catch(Exception $ex){
//Process the exception
}
If there is an error outputted by the function, just # to hide the error and handle the incorrect output of $translate_feed or $translate manually.
You can try failing it on purpose by simply passing an invalid URI to file_get_contents and then forcefully feed non XML or invalid XML to simplexml_load_string to see what happens.
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
if ( $translate_feed === false )
{
echo "failed";
}
You can do like this
if(#file_get_contents("yourFilePath.txt")){
echo "success";
}
/*
It's a modified file_get_contents()
get_contents(filename, use_include_path, context, offset, maxlen)
*/
function get_contents($url, $u = false, $c = null, $o = null) {
$headers = get_headers($url);
$status = substr($headers[0], 9, 3);
if ($status == '200') {
return file_get_contents($url, $u, $c, $o);
}
return false;
}
echo get_contents('https://example.com/');
there is $http_response_header variable is being created in local scope that we can use it to check headers returned from server. Here is my implementation:
public function getData($url)
{
try {
$response = #file_get_contents($url);
if (isset($http_response_header)) {
if (!in_array('HTTP/1.1 200 OK', $http_response_header) &&
!in_array('HTTP/1.0 200 OK', $http_response_header)) {
throw new \Exception('Server did not return success header!');
}
}
return $response;
} catch (\Exception $ex) {
throw new TransportException($ex->getMessage(), $ex->getCode(), $ex);
}
}
if( !$translate_feed) return "Failed";
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$result=$text;
if ($translate_feed) {
$translate = simplexml_load_string($translate_feed);
if (is_array($translate)) $result=$translate[0];
}
return $result;

Categories