I'm following the Rest sample (PaymentWithCreditCard) and I can't figure out how to get the actual Error code.
Payment pymnt = new Payment();
pymnt.intent = "sale";
pymnt.payer = payr;
pymnt.transactions = transactions;
try
{
APIContext apiContext = Configuration.GetAPIContext();
Payment createdPayment = pymnt.Create(apiContext);
catch (Exception Ex)
{
// how can I get the Error code??
}
How can tie the general Exception to the list of Error codes (https://developer.paypal.com/docs/classic/api/errorcodes/)?
Thanks.
Related
Based on the link I tried tried working and here is the code I tried out
public static void SendNotification2(String appid, String pinpointEndpointId){
try {
GetEndpointRequest getEndpointRequest = new GetEndpointRequest()
.withApplicationId(appid)
.withEndpointId(pinpointEndpointId);
AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
GetEndpointResult endpointResult = pinpoint.getEndpoint(getEndpointRequest);
EndpointResponse endpointResponse = endpointResult.getEndpointResponse();
Map<String, String> data = new HashMap<String, String>();
data.put("message", "test");
DirectMessageConfiguration directMessageConfiguration =
new DirectMessageConfiguration().withGCMMessage(new GCMMessage().withData(data).withSilentPush(true));
AddressConfiguration addressConfiguration = new AddressConfiguration().withChannelType(ChannelType.GCM);
MessageRequest messageRequest = new MessageRequest().withMessageConfiguration(directMessageConfiguration)
.addAddressesEntry(endpointResponse.getAddress(), addressConfiguration);
SendMessagesRequest sendMessagesRequest = new SendMessagesRequest()
.withApplicationId(appid)
.withMessageRequest(messageRequest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The code executes successfully without any error/exception but i do not see the notification.
However when i post the message from "Direct Messaging" section of pinpoint with the Endpoint Id I am able to see the notification in mobile.
Also using Amazon CLI the Notification message is delivered:
aws --region="us-east-1" pinpoint send-messages --application-id 1fd19ca6fa944a79bdd91beddb4b4f7e --message-request "{\"Context\":{},\"MessageConfiguration\":{\"DefaultMessage\":{\"Body\":\"Test from default message\",\"Substitutions\":{}},\"DefaultPushNotificationMessage\":{},\"APNSMessage\":{},\"GCMMessage\":{\"Data\":{\"message\":\"test\"},\"SilentPush\":true},\"BaiduMessage\":{},\"ADMMessage\":{},\"SMSMessage\":{}},\"Addresses\":{\"cltaa5owuOU:APA91bFOBUB5YRi_Ac6teNmuu19aoFDAByOeoVbqLmY1Yp6cZEp_aueunDU1ZPB6H50GKBfuxu300z-El_sEjxo72crYKnklI-wboxXDk180JICrif0c7R-fR4xFOm5WsQOGUJZPFLG6\":{\"ChannelType\":\"GCM\"}},\"Endpoints\":{}}
Any help will be appreciated.
Thanks
I have the next problem: I've made a simple application which retrieves information from a server (GET Method). The application works fine as long as the information is retrieved successfully.
In case of insuccess, I don't receive the error from the server (ex: 401 - Unauthorized, 403 - Forbidden - when the authentication token is incorrect for example).
How can I fix this so that my application will return the error from server ? I've done also a POST method and there it's working, I received all erorrs froem server in case of insuccess.
What i'm doing wrong with this code ? Why i don't receive an error in case of insuccess?
The only error I receive in output is 400 in all scenarios and this isn't enough.
For example, if the authorization token is incorrect, I should receive from server 401 - Unauthorized. I know this because i'm doing test with other REST application (like POSTMAN). Can it be fixed to show the errors related to that scenarios ?
void example2() {
// GET METHOD !
try {
String webPage = "https://www.clients.ro";
String name = "user";
String password = "pass";
String authString = name + ":" + password;
System.out.println("Decoded authorization token" + authString);
//byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
//String authStringEnc = new String(authEncBytes);
byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);
String authStringEnc = DatatypeConverter.printBase64Binary(authEncBytes);
System.out.println("Token encoded in Base64 " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println(result);
System.out.println();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm using Facebook ads api SDK for .net (http://www.nuget.org/packages/Facebook/6.4.2) and when I catch an error, the message is always the same general error in the exception message object:
(FacebookApiException - #100) Invalid parameter
It happens since I moved to the versioned calls (v2.2) - before that I used the unversioned calls and it was fine. For example, this is how I get the error (using regular try catch in c#):
try
{
FacebookClient facebookClient = new FacebookClient();
facebookClient.AccessToken = "<YOUR_ACCESS_TOKEN>"
Dictionary<string, object> parameters = new Dictionary<string, object>();
string name = Guid.NewGuid().ToString();
parameters.Add("name", name);
parameters.Add("conversion_specs", "");
parameters.Add("campaign_id", "6024570447800");
parameters.Add("creative", "{\"creative_id\":\"6024570452200\"}");
parameters.Add("redownload", "false");
parameters.Add("tracking_specs", "");
parameters.Add("view_tags", "[]");
var result = facebookClient.Post("v2.2/act_107893676040337/adgroups", parameters) as IDictionary<string, object>;
}
catch (Exception ex)
{
FacebookApiException fbEx = ex as FacebookApiException;
string errorMsg = fbEx.Message;
}
It happens because Facebook changed the return error object and added 2 new fields: error_user_title, error_user_msg.
Is there a way to access these fields in the FacebookApiException object ?
How can I extract the relevant error message?
I dived into this issue and it's not a Facebook problem. The problem is in the third party SDK.
I contacted the development team, they aware of this issue and fixed it in the last beta version.
Given a REST service call
http://acme.com/app/widget/123
returns:
<widget>
<id>123</id>
<name>Foo</name>
<manufacturer>Acme</manufacturer>
</widget>
This client code works:
RestTemplate restTemplate = new RestTemplate();
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.getXStream().processAnnotations(
new Class[] {
Widget.class,
ErrorMessage.class
});
HttpMessageConverter<?> marshallingConverter = new MarshallingHttpMessageConverter(
xStreamMarshaller, xStreamMarshaller);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(marshallingConverter);
restTemplate.setMessageConverters(converters);
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 123L);
However, calling http://acme.com/app/widget/456 returns:
<error>
<message>Widget 456 does not exist</message>
<timestamp>Wed, 12 Mar 2014 10:34:37 GMT</timestamp>
</error>
but this client code throws an Exception:
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 456L);
org.springframework.web.client.HttpClientErrorException: 404 Not Found
I tried:
try {
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 456L);
}
catch (HttpClientErrorException e) {
ErrorMessage errorMessage = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", ErrorMessage.class, 456L);
// etc...
}
The second invocation just threw another HttpClientErrorException, plus it does not feel right calling the service twice.
Is there a way to call the service once and parse the response into a Widget on success and an ErrorMessage when not found?
Following from my comment, I checked the HttpClientErrorException JavaDoc and it does support both setting/getting the statusText as well as the responseBody. However they are optional and RestTemplate may not populate them - you'll need to try something like:
try {
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 456L);
}
catch (HttpClientErrorException e) {
String responseBody = e.getResponseBodyAsString();
String statusText = e.getStatusText();
// log or process either of these...
// you'll probably have to unmarshall the XML manually (only 2 fields so easy)
}
If they are both empty/null then you may have to extend the RestTemplate class involved and populate those fields yourself and/or raise a Jira issue on the Spring site.
You can also create an object from Error response body if you like:
ObjectMapper om = new ObjectMapper();
String errorResponse = ex.getResponseBodyAsString();
MyClass obj = om.readValue(errorResponse, MyClass.class);
As you already catch the HttpClientErrorException object, it should allows you to easily extract useful information about the error and pass that to the caller.
For example:
try{
<call to rest endpoint using RestTemplate>
} catch(HttpClientErrorException e){
HttpStatus statusCode = e.getStatusCode();
String body = e.getResponseBodyAsString();
}
IMO if one needs to further de-serialize the error message body into some relevant object, that can be handled somewhere outside of the catch statement scope.
I too have found this a disturbing change in the Spring library. You used to be able to throw a ResponseStatusException and pass it the HttpStatus code and a custom message and then catch the HttpClientErrorException and simply print getMessage() to see the custom error. This no longer works. In order for me to print the custom error, I had to capture the ResponseBody as a String, getResponseBodyAsString on the HttpClientErrorException. Then I needed to parse this as a String doing some pretty hokey substring manipulation. Doing this strips out the information from the ResponseBody and gives the message sent by my server. The code to do this follows:
String message = hce.getResponseBodyAsString();
int start, end;
start = message.lastIndexOf(":", message.lastIndexOf(",")-1) + 2;
end = message.lastIndexOf(",") -1;
message = message.substring(start, end);
System.out.println(message);
When I test this using ARC or Postman, they can display the correct message after I add server.error.include-message=always to my application.properties file on the server. I am not sure what method they are using to extract the message but that would be nice to know.
I am working in .NET, using the QuickBooks V2 API to try and fetch a count of the number of Items the user's QBD.
Does anyone have a working example of how to implement the "RecordCountQuery" class to find the # of Items in QBD?
Here is one of my attempt to do so:
//
// Get a record count of the items
//
var qbItemsCount = new RecordCountQuery();
var myResults = qbItemsCount.ExecuteQuery<Item>(_oQBIDataServices.ServiceContext);
Error:
Intuit.Ipp.Exception.IdsException was unhandled by user code
HResult=-2146233088
Message= The RecordCountQuery xml must wrap an existing supported query object. Please modify your query and try again.
Source=""
ErrorCode=-2015
I gather by this that I should be using an different type in the "ExecuteQuery" method like Intuit.Ipp.Data.QBD.ItemQuery. I tried this but got a different error.
So what I am asking for is not necessarily correction to the above code, but a WORKING EXAMPLE of the RecordCountQuery class in .NET.
Thank you.
Edit - Adding .net code
RecordCountQuery query = new RecordCountQuery();
CustomerQuery custQuery = new CustomerQuery();
query.Item1 = custQuery;
List<RecordCount> customerRecordCountQuery = query.ExecuteQuery<RecordCount>(context).ToList();
string customerCount = customerRecordCountQuery[0].Count;
I hv a working java code. Please check if it is useful.
API endpoint - https://services.intuit.com/sb/recordcount/v2/{*relam_id*}
POST body
<RecordCountQuery xmlns="http://www.intuit.com/sb/cdm/v2">
<CustomerQuery/>
</RecordCountQuery>
Response
<?xml version="1.0" encoding="UTF-8"?><!--XML GENERATED by IntuitDataSyncEngine (IDS) using \\SBDomainServices\CDM\branches\3.9.0-rel-1-->
<RestResponse xmlns="http://www.intuit.com/sb/cdm/v2"
xmlns:xdb ="http://xmlns.oracle.com/xdb"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://www.intuit.com/sb/cdm/v2 ../common/RestDataFilter.xsd"><RecordCounts>
<RecordCount>
<ObjectName>Customer</ObjectName>
<Count>392</Count>
</RecordCount>
</RecordCounts></RestResponse>
Java Code
public int testGetCount() {
int objectCount = 0;
try {
QBCustomerQuery CustomerQuery = QBObjectFactory.getQBObject(
context, QBCustomerQuery.class);
QBDRecordCountService iRecordCountSer = QBDServiceFactory
.getService(context, QBDRecordCountService.class);
List<QBRecordCountImpl> recordCounts = iRecordCountSer.getCount(
context, CustomerQuery);
Iterator<QBRecordCountImpl> iterator = recordCounts.iterator();
while (iterator.hasNext()) {
QBRecordCountImpl next = iterator.next();
objectCount = Integer.parseInt(next.getCount().toString());
}
System.out.println("Customer count - " + objectCount);
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return objectCount;
}
Thanks