How to try catch block in Jmeter.Webdriver webdriver Sampler - webdriver

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

Related

Error handling when ElementNotVisible in dropdown in Selenium code

I have this following code. Please let me know if there is a way to capture the error and display it when the selectedAVE item is not found in the dropdown.
FlexWebDriver
.call(webDriver,
"container_app",
"doFlexClick",
"TreeNodeItem_com.vmware.ebr2.category/_TreeNodeItem_HGroup1/nodeName",
"");
Thread.sleep(SLEEP_TIME);
DropDownList.clickToOpen(webDriver, "vdrCombo");
Thread.sleep(SLEEP_TIME);
FlexMouseEvents.leftClick(webDriver, "automationName=" + selectedAVE);
You can use Try Catch() to handle the run time exceptions.
Try{
DropDownList.clickToOpen(webDriver, "vdrCombo");
Thread.sleep(SLEEP_TIME);
FlexMouseEvents.leftClick(webDriver, "automationName=" + selectedAVE);
}catch(Throwable e){
system.out.println(e.getMessage())
}

Refit.ApiException Error Handling

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);
}

Stop execution of a page

I have a task board, some person is working on some task, if task is assigned to another person by his manager the first person who is working on the task board, his execution should be stopped, and a message should be displayed that "This task is assigned to some one else."
I tried using following in page load.
//Code Behind
if (!Owner)
{
SomecontrolsToHide();
MessageDisplay(); // JavaScript function call using RegisterStartupScript()
Response.End();
}
protected void MessageDisplay()
{
string dbMessage = "Task is assigned to someone else.";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(typeof(Page), "ShowMessageWrapup_" + UniqueID, "showMessageDisplay('','" + dbMessage + "');", true);
}
// JavaScript function that displays message.
function showMessageDisplay(args, displayMessage) {
if (displayMessage != "") {
document.getElementById("spanMessage").innerHTML = displayMessage;
document.getElementById("spanMessage").style.display = 'inline';
}
}
It stops the execution but message is not displayed and Controls are not hidden too.
What should I do?
Don't do Response.End(). Just return without doing anything.
This will show the message box. Try this.
Response.Write(#"<script language='javascript'>alert('You are not allowed for this task !!!')</script>");

Is it possible to find the function and/or line number that caused an error in ActionScript 3.0 without using debug mode?

I'm currently trying to implement an automated bug reporter for a Flex application, and would like to return error messages to a server along with the function/line number that caused the error. Essentially, I'm trying to get the getStackTrace() information without going into debug mode, because most users of the app aren't likely to have the debug version of flash player.
My current method is using the UncaughtErrorEvent handler to catch errors that occur within the app, but the error message only returns the type of error that has occurred, and not the location (which means it's useless). I have tried implementing getStackTrace() myself using a function name-grabber such as
private function getFunctionName (callee:Function, parent:Object):String {
for each ( var m:XML in describeType(parent)..method) {
if ( this[m.#name] == callee) return m.#name;
}
return "private function!";
}
but that will only work because of arguments.callee, and so won't go through multiple levels of function calls (it would never get above my error event listener).
So! Anyone have any ideas on how to get informative error messages through the global
error event handler?
EDIT: There seems to be some misunderstanding. I'm explicitly avoiding getStackTrace() because it returns 'null' when not in debug mode. Any solution that uses this function is what I'm specifically trying to avoid.
Just noticed the part about "I don't want to use debug." Well, that's not an option, as the non-debug version of Flash does not have any concept of a stack trace at all. Sucks, don't it?
Not relevant but still cool.
The rest is just for with the debug player.
This is part of my personal debug class (strangely enough, it is added to every single project I work on). It returns a String which represents the index in the stack passed -- class and method name. Once you have those, line number is trivial.
/**
* Returns the function name of whatever called this function (and whatever called that)...
*/
public static function getCaller( index:int = 0 ):String
{
try
{
throw new Error('pass');
}
catch (e:Error)
{
var arr:Array = String(e.getStackTrace()).split("\t");
var value:String = arr[3 + index];
// This pattern matches a standard function.
var re:RegExp = /^at (.*?)\/(.*?)\(\)/ ;
var owner:Array = re.exec(value);
try
{
var cref:Array = owner[1].split('::');
return cref[ 1 ] + "." + owner[2];
}
catch( e:Error )
{
try
{
re = /^at (.*?)\(\)/; // constructor.
owner = re.exec(value);
var tmp:Array = owner[1].split('::');
var cName:String = tmp.join('.');
return cName;
}
catch( error:Error )
{
}
}
}
return "No caller could be found.";
}
As a side note: this is not set up properly to handle an event model -- sometimes events present themselves as either not having callers or as some very weird alternate syntax.
You don't have to throw an error to get the stack trace.
var myError:Error = new Error();
var theStack:String = myError.getStackTrace();
good reference on the Error class
[EDIT]
Nope after reading my own reference getStackTrace() is only available in debug versions of the flash player.
So it looks like you are stuck with what you are doing now.

Why is this app blocking?

I just tried some code from the internet and ran it, but it blocked my emulator. The code is:
public void getcontents()
{
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try
{
c = (HttpConnection)Connector.open("http://www.java-samples.com",Connector.READ_WRITE, true);
c.setRequestMethod(HttpConnection.GET); //default
is = c.openInputStream(); // transition to connected!
int ch = 0;
for(int ccnt=0; ccnt < 150; ccnt++) { // get the title.
ch = is.read();
if (ch == -1){
break;
}
sb.append((char)ch);
}
}
catch (IOException x){
x.printStackTrace();
}
finally{
try{
is.close();
c.close();
} catch (IOException x){
x.printStackTrace();
}
}
System.out.println(sb.toString());
}
I called the function with an OK command.
The emulator got blocked until I killed the process.
How do I solve this?
Try stepping through the code in the debugger. Or at the very least add some log statements. My guess is that the stream is waiting on data from the HTTP connection and isn't getting flushed but I haven't ran the code to verify that assertion.
The only loop I can see in your code is the for loop, which is finite (no more that 150 iterations), so that would not make the code execute indefinitely.
What I would suggest is place a number of debug output statements (output to a console or even dialog box alerts) at various points through the code. This will help you work out which line of code is causing the problem. For instance, if you put a line before and after the for loop and, when executing, only the first one is displayed, you know your problem is somewhere within the loop. You can then narrow it down by putting debug lines within the loop (including the loop number) to find out which line exactly is causing your problem.
Try checking the response code before attempting to read the response body from the server. This will either confirm the connection succeeds or print out the error response. Place the following after the call to Connector.open() :
if (c.getResponseCode() != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + c.getResponseCode());
} else {
System.out.println("**Debug** : HTTP_OK received, connection established");
}
If running the code then gives no output of either the exception or the HTTP confirmation then you are likely blocking on the connection attempt (check your emulator's connectivity to the internet). If you do get the HTTP_OK then you are likely blocking on the server's HTTP response, or lack thereof. Posting a comment with your results would be a good idea.

Resources