Refit.ApiException Error Handling - refit

How do I get to the content of Refit.ApiException?
Depending on what the inner content is, I want to let the user know how to proceed. So I see that thrown exception has the following content ...
Content "{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}"
The question is, how do I access that?

You can add one catch block for ApiException. and you can get content from this catch block.
See below:
catch (ApiException ex)
{
var content = ex.GetContentAs<Dictionary<String, String>>();
Debug.WriteLine(ex.Message);
}

Going through the RestService class https://github.com/paulcbetts/refit/blob/master/Refit/RestService.cs
figured out I could use the GetContentAs method
So just did this..
((Refit.ApiException)ex).GetContentAs<Dictionary<String, String>>())
to parse out the key value content.

As an extra heads-up:
GetContentAs<T>(); is now deprecated.
Use GetContentAsAsync<T>(); instead.

With the latest version of API Exception, you can use the following code for getting the API content:
public static void HandleException( Exception exception )
{
var content = ((Refit.ApiException)exception).GetContentAsAsync<Dictionary<string, string>>();
var message = content.Result.FirstOrDefault( pair => pair.Key == "message" ).Value;
Debug.WriteLine(message);
}

Related

How to overcome error from a single javascript while enabling others in HTMLUnit?

I am new to HTMLUnit. I am trying to get information from a public site (given in the code below). While I can open this public url in Chrome browser or Chrome Selenium extension without error and continue functioning with it, my HTMLUnit program is throwing an error as below which it seems is stemming from a particular Javascript in the page. My question is, how to resolve this kind of problem ? I cannot disable the javascript altogether as the form section with details will not be available in that case. However if I use the command
EcmaError: lineNumber=[55] column=[0] lineSource=[] name=[TypeError] sourceName=[https://www.marutisuzuki.com/js/server_cookies.js] message=[TypeError: Cannot find function fetchServerCookie in object [object Object]. (https://www.marutisuzuki.com/js/server_cookies.js#55)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot find function fetchServerCookie in object [object Object]. (https://www.marutisuzuki.com/js/server_cookies.js#55)
String pageAsXml = null;
String pageAsText = null;
try{
WebClient webClient = new WebClient(BrowserVersion.CHROME);
HtmlPage page =
webClient.getPage("https://www.marutisuzuki.com/dealer-showrooms/");
//webClient.getOptions().setJavaScriptEnabled(false);
pageAsXml = page.asXml();
pageAsText = page.asNormalizedText();
System.out.println(pageAsText);
}
catch(Exception e) {
e.printStackTrace();
}
You can use
webClient.getOptions.setThrowExceptionOnScriptError(false);
For more have a look at https://htmlunit.sourceforge.io/javascript-howto.html.
BTW: this is an error in the page itself because you got the same in real browsers.

How to try catch block in Jmeter.Webdriver webdriver Sampler

I want to do the exception handling in Jmeter.Webdriver Webdriver Sampler
Please let me , How to use try/catch block in Jmeter.Webdriver webdriver Sampler ?
You can do this via normal JavaScript try block, here is an example of taking a screenshot when error occurs:
var pkg = JavaImporter(org.openqa.selenium)
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
var wait = new support_ui.WebDriverWait(WDS.browser, 5)
var exception = null
WDS.sampleResult.sampleStart()
try {
WDS.browser.get('http://example.com')
wait.until(conditions.presenceOfElementLocated(pkg.By.linkText('Not existing link')))
} catch (err) {
WDS.log.error(err.message)
var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
screenshot.renameTo(java.io.File('screenshot.png'))
exception = err
} finally {
throw (exception)
}
WDS.sampleResult.sampleEnd())
Don't forget to "throw" the error after you handle it otherwise it will be "swallowed" and you get a false positive result.
See The WebDriver Sampler: Your Top 10 Questions Answered article for more tips and tricks
Surround the code with try block and add catch block at the end by giving variable name to capture the exception. (in the example, it is exc)
try as follows:
try{
WDS.sampleResult.sampleStart()
WDS.browser.get('http://jmeter-plugins.org')
var pkg = JavaImporter(org.openqa.selenium)
WDS.browser.findElement(pkg.By.id('what')) // there is no such element with id what
WDS.sampleResult.sampleEnd()
}
catch(exc){ //exc variable name
WDS.log.error("element not found" + exc)
}
in the JMeter log, you can see the complete trace of NoSuchElementException, which is raised when trying to find the element by id with the values as what, which is not present in the HTML.
Note: use View Results in Table to see the Sampler response time.
Reference:
https://jmeter-plugins.org/wiki/WebDriverSampler/
Reference Image:
It is same as how do you do in other IDEs like eclipse.
you can see below code
//try block starts here
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element"))).click();
}
catch(Exception e)
{
WDS.log.info("Exception is : " +e);//you can print the exception in jmeter log.
}
double quotes should be replaced with the single quote if you are using javascript Since the BeanShell is easy and it is similar to java use BeanShell as much as possible

Clarification on putting a google calender entry from java

I am trying to put an entry in google calendar from my application. Just a simple text title, content and date entries. Please find below the code snippet which am trying to use;
public void temp() {
URL postURL = null;
try {
postURL = new URL("http://www.google.com/calendar/feeds/MAILID#gmail.com/PASSWORD/full");
EventEntry eventEntry = new EventEntry();
eventEntry.setTitle(new PlainTextConstruct("One"));
eventEntry.setContent(new PlainTextConstruct("Two"));
When eventTime = new When();
eventTime.setStartTime(DateTime.parseDateTime("2016-03-09T15:00:00-08:00"));
eventTime.setEndTime(DateTime.parseDateTime("2016-03-09T15:00:00-08:00"));
eventEntry.addTime(eventTime);
CalendarService calendarService = new CalendarService("Savor");
EventEntry createdEvent = calendarService.insert(postURL, eventEntry);
} catch (Exception e) {
e.printStackTrace();
}
}
When executing this, am getting the service forbidden exception;
[Ignore the line numbers though]
com.google.gdata.util.ServiceForbiddenException: Forbidden
<HTML>
<HEAD>
<TITLE>Forbidden</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Forbidden</H1>
<H2>Error 403</H2>
</BODY>
</HTML>
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:605)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.insert(Service.java:1409)
at com.google.gdata.client.GoogleService.insert(GoogleService.java:613)
at GCalender.temp(GCalender.java:65)
at GCalender.main(GCalender.java:88)
The exception is being thrown at this line: EventEntry createdEvent = CalendarService.insert(postURL, eventEntry);
Any one faced the same issue already? Kindly provide your inputs, Thanks.
Let's back track your code.
In order for you to create a Calendar successfully, these are your checklist:
set your OAuth scope to https://www.googleapis.com/auth/calendar.
ensure the authenticated user has write access to the calendar with the calendarId you provided (for example by calling calendarList.get()
for the calendarId and checking the accessRole).
Other things to check like enabling the API in developer console, oauth key can be viewed in this guide(if you are not using service account to access the calendar). If you are using your a service account then go to this link.

Flyway: Using both custom and Java Callbacks

If I specify
flyway.callbacks=com.myclass.CustomCallBack
it gets called fine, but I notice it seems to suppress the SQL callback functionality. Is there any way to have both? I notice there's a SqlScriptFlywayCallback, but that's one of your 'internal' classes....
Currently the only way is to refer both to the internal class and your own. Please file an enhancement request in the issue tracker.
As a simple workaround, you can initialize the SqlScriptFlywayCallback as Axel suggested. Here's how I did it, given an initialized instance of flyway:
DbSupport dbSupport;
try {
dbSupport = DbSupportFactory.createDbSupport(flyway.getDataSource().getConnection(), false);
} catch (SQLException e) {
throw new RuntimeException("Could not get connection to database");
}
final FlywayCallback runSqlCallbacks = new SqlScriptFlywayCallback(
dbSupport,
flyway.getClassLoader(),
new Locations(flyway.getLocations()),
new PlaceholderReplacer(flyway.getPlaceholders(),
flyway.getPlaceholderPrefix(),
flyway.getPlaceholderSuffix()),
flyway.getEncoding(),
flyway.getSqlMigrationSuffix()
);
flyway.setCallbacks(
runSqlCallbacks,
new MyCallback(...));

HttpRequestValidationException - How to get full value entered?

We receive multiple HttpRequestValidationExceptions on our website. We catch these appropriately, but would like to start logging them in more detail. The message that is caught shows
"A potentially dangerous Request.Form value was detected from the client (ctl00$txtSearch=\"<a href=\"www.google.com...\")."}
We would like to know the full text of what was entered in the text box and will do nothing except log it. I know that I entered
www.google.com
but as you can see, it did not show all of that in the Message part of the exception. InnerException is null, so that is of no help.
This is the code we use:
void Application_Error(object sender, EventArgs e)
{
// Get the last exception that has occurred
if (Server.GetLastError() != null)
{
var ex = Server.GetLastError().GetBaseException();
//...log it here
}
}
How can we get the full text entered into the text box? Turning off the page validation is not an option. Thank you in advance!
Use Request.Form["key name"] after catching last exception.
var val = Request.Form["txtInput1"];
You can also use
foreach (string key in Request.Form.AllKeys)
{
//Log everything.
var x = Request.Form[key];
}
Above I had tbSource as a text box and capturing the Value on Application_Error

Resources