Join us on :

Errors in Protractor

An Error is an unplanned surprise that occurs during execution of program, the exception has power to stop the program execution.

In Typescript/JavaScript , we don't have Exception, we call it as error. Without a doubt Error stops the execution, but we are more powerful than exception so we can handle the exception without stopping the execution of the program.

These errors will occur at execution time , not in compile time. When run time error occurs , we can't handle that error. we must change the code to remove error.

Error are two types (purely based on my assumptions):

  • Normal(synchronous error) : errors happen at runtime you can handle them with try..catch
  • Asynchronous Errors : errors happens at runtime, you cannot handle them as they return the error in the form of promises

Protractor errors are asynchronous Errors ones, so you can skip to protractor errors if you want.

Error :

Error is main interface in Typescript, It contains two properties name and message, we don't get this error , we get its child interfaces.
They are :

  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

interface Error {
	name: string;
	message: string;
}

Try..Catch..Finally

You might have come across situations where your program got stopped abruptly throwing some error.

Error (recap): Exception is abnormal behavior of the code or it happens because something is wrong with our code or with our system.

Here, abnormal behavior means something or wrong with our code something unexpected. For example, program throws an exception when we try to access a file which is not present in our local system, etc..

try :

try block is nothing but a block which contains a certain code and that certain code may or may not behave abnormally, when the code behaves abnormally the program throws an exception but when it behaves normally it will not throw any error.

In layman terms, try block is nothing but a room in hospital which is little sensitive and we are having patient inside the particular room, when something unexpected happens in that room the hospital will be ready to handle the situation.

When an error occurs in try block, the code after the error in the try block will not be executed.


									try{
										// code that we need to monitor
										}
									

catch :

The catch block is nothing but a block of code, so whenever something abnormal happens in the try block the associated catch block will be executed, the catch block will be having code which will efficiently handle that particular exceptional situation

In catch block user should mention what is the error that we should handle because we cannot handle all the error as different error will require a different code to handle the situation.

Catch block will not be executed if there is no error occurs in try block


									try {
									   throw 'myException'; // generates an exception
									}
									catch (e) {
									   // statements to handle any exceptions
									   logMyErrors(e); // pass exception object to error handler
									}
									


Program for simple try and catch block, here we are trying to print the error details instead of stopping the execution when error arises


									describe("Page Object Model in Protractor",function(){
									  it("Exception in Typescript",function(){
									  
										try {
										  throw new Error('Something bad happened');
										}
										catch(e) {
										  console.log(e);
										}
									  });
									});
									


try-catch-typescript-protractor-exceptions Above program throws exception and the catch will be executed, the content in the catch block will be executed.


finally :Finally block is also a normal block which contains code but finally block will be executed irrespective of whether an exception occurred or not in try block

Basic rules of finally :

  • finally block will be used to perform code clean up activities like : disconnecting browser, closing all files, closing the browser.
  • try block is must to write finally block
  • Only one finally block is allowed with try block
When finally block will not execute :

  • When System.exit() code occurs in try or in catch block
  • When JVM crashes
  • When try block is executed infinitely without breaking
  • When user stopped the execution (just for fun).


In below program, the code present in try block will throw an exception and the catch block will be executed, then finally block gets executed

Program with try..catch..finally


									describe("Errors in Protractor",function(){
									  it("Errors in Typescript",function(){
										try {
										  throw new Error('Something bad happened');
										}
										catch(e) {
										  console.log(e);
										}finally{
										  console.log("I am DAMN Adamant, So i execute everytime")
										}
									  });
									});
									


try-catch-finally-typescript-protractor

In below program, the code present in try block will not throw any exception so the catch block will not be executed as the catch block gets executed when there is an exception in the try block, at last finally block will be executed after the try block.


									it("Errors in Typescript",function(){
										try {
										  console.log("I am not throwing any exception")
										}
										catch(e) {
										  console.log(e);
										}finally{
										  console.log("I am DAMN Adamant, So i execute everytime")
										}
									  });
									


try-catch-finally-no-error-typescript-protractor

finally block without catch block : Try block expects either catch block or finally block to present or both catch and finally blocks to present but writing both catch and finally block is not mandatory.

Program for try block without catch block


									it("Errors in Typescript",function(){
										try {
										  throw new Error('Something bad happened');
										}
										finally{
										  console.log("I am DAMN Adamant, So i execute everytime")
										}
									});
									


Basic rules of try..catch..finally :

  • The code present in try block may or may not raise the error
  • try block or catch or finally blocks cannot exits alone
  • catch or finally or both should follow try block
  • catch block is optional when finally block is present
  • finally block is optional when catch block is present
  • There is no block which executes when only an error is not occurred in typescript ( but exists in python language)
  • We can't have catch or finally block without a try statement.
  • We can't write any code between try..catch..finally block.
  • try..catch blocks can be nested ( try inside another try or catch or finally)
  • We can have only one finally block with a try block.
The purpose of the try catch block is to continue the execution of program without stopping the execution whenever there is an exception

Multiple catch blocks with try block

Java lets the user to write multiple catch block, multiple catch block is nothing but having more than one catch block per try block.

Compiler decides to which catch block should be executed if the exception mentioned in Catch block and the actual exception raised are matches.

We can write n-number of catch blocks, but make sure that you are writing the exceptions from narrow to broad. What I mean is we should write the specific exception in the first catch and little less specific or parent of specific exception in second catch block so on


										try {
											// exception throwing code
										} catch (e if e instanceof TypeError) {
											// statements to handle TypeError exceptions
										} catch (e if e instanceof RangeError) {
											// statements to handle RangeError exceptions
										} catch (e if e instanceof EvalError) {
											// statements to handle EvalError exceptions
										} catch (e) {
											// statements to handle any unspecified exceptions
											console.log(e); // pass exception object to console
										}
										


Basic rules for catch block :

1. Only one catch block will be executed per exception and only one exception can raise at a time
2. We should order the catch block from narrow type exception to broad.
3. We cannot have more than one catch block with a particular exception, if we try to do so the second catch block will give error saying 'not reachable code'

More than Two Browser Windows

Nested try..catch..finally blocks

When a try..catch block is present inside another try..catch block then it is called as nested try..catch. We can write a try..catch..finally inside a try block of code.

In below code inner try block throws NoSuchElementException and we have catch block with same exception to handle the exception, then finally block of the inner try will be executed.

Once inner try..catch..finally block is over, the control comes to outside catch block as there is no exception is remaining in outer try block so catch block will not be executed, but finally in outer catch block will be executed.


										try {
										  try {
											throw new Error('oops');
										  }
										  finally {
											console.log('finally');
										  }
										}
										catch (ex) {
										  console.error('outer', ex.message);
										}
										

We can write the nested try catch block inside catch and finally blocks as well.


Outer catch block handles errors raised by inner try block :
If any error occurred in inner try block will be handled by the inner catch block, but if inner catch is not able to handle the exception then the outer catch block tries to handle the exception raised by the inner try block.

So whenever we write nested try catch block the inner catch block always will have more than one catch block by default.

throw keyword in errors

So far, we are trying to catch and handle the errors. Before you can catch an error, some code somewhere must throw error

Any code can throw an error: your code, code from a package written by someone else such as the packages that come with the Typescript

Regardless of what/who throws the error, it's always thrown using throw statement.

Below program throws error with some reason, we can throw any error using throw keyword.


										try {
											throw new Error('oops');
										}
										finally {
											console.log('finally');
										}
										

FFE : Frequently Faced Exception in Typescript

Common properties among Errors :

  • They extend Error interface , that means they are a child interfaces of Error
  • They doesn't contain any properties or functions of its own.
  • However They extend Error interface, they will have Error interface properties.

EvalError:

  • The EvalError object indicates an error regarding the global eval() function.
  • That means this error will occur when dealing with eval() function

RangeError:

  • The RangeError object indicates an error when a value is not in the set or range of allowed values.
  • A RangeError is thrown when trying to pass a number as an argument to a function that does not allow a range that includes that number

ReferenceError:

  • The ReferenceError object represents an error when a non-existent variable is referenced.
  • A ReferenceError is thrown when trying to dereference a variable that has not been declared.

SyntaxError:

  • The SyntaxError object represents an error when trying to interpret syntactically invalid code.

TypeError:

  • The TypeError object represents an error when a value is not of the expected type

URIError :

  • The URIError object represents an error when a global URI handling function was used in a wrong way.

Errors in Protractor

Karthiq, we have tried all the above said bullshit but none of it seems working, are you thinking so ?. Then you are in right part of the page.

You have a block of code that throws an error, You have tried putting it inside a try..catch block but it still does not get caught.

So far, you might have tried something like this (which didnot work):


										try {
										  element(by.name("some_stupid_locator")).click()
										}catch(e){
										  console.log("exception occurred")
										}
										finally{
										  console.log("I am DAMN Adamant, So i execute every time")
										}
										

What is asynchronous code :

Asynchronous error is uncatchable with try..catch block and this error will propagate all the way and terminate the program.

I hope you do remember that :

Protractor works Asynchronously and provides promise when you want to retrieve the value. Similar to this all the error in the protractor are promises containing error.

To handle a promise we have to resolve it and then we have to check whether it is promise with value or exception.

Syntax for handling protractor errors: protractor-error-handling-asynchonous-error

In above image, i have used the then(null, function(err){, let me explain this.

Try to click the value and protractor tried, if the operation happened in right way like if element is there and protractor clicked it, Then the then block might have received nothing as operation is over and the operation(click) returns nothing. So it will not enter the then block.

But if operation is failed then that operation return error, that is what we are trying to retrieve in the then block, so when there error we will get it with then(null, function(err){, now err caught the error and its details.

We can retrieve the error and its details from err variable, and we can perform any operation we want to perform.


import { browser, element, by } from "protractor";
describe("Errors in Protractor",function(){
  browser.ignoreSynchronization = true; // for non-angular websites
  it("Error handling in protractor",function(){
  
    browser.get("https://google.com")
    element(by.name("some_stupid_locator")).click()
    .then(null, function(err){
      console.log("he error occurred is : "+ err.name)
      // click i am feeling lucky button
      element(by.name("btnI")).click()
    })
    
  });
});

the Obvious question Now you might have got some question, karthiq it is okay for clicking an element as it return nothing but How would I work with function which return promises and values like getAttribute(), getText(), getCssValue().

As I said, then(null, function(err){ will receive the exception nothing else, if there is no error then the then(null, function(err){ will not be executed.

So we have to get the values from the function using another then block, which is normal then block.


import { browser, element, by } from "protractor";
describe("Errors in Protractor",function(){
  browser.ignoreSynchronization = true; // for non-angular websites
  it("Error handling in protractor",function(){
  
    browser.get("https://google.com")
    element(by.name("btnI")).getAttribute("aria-label")
    .then(null, function(err){
      console.log("The error occurred is : "+ err.name)
    })
    .then(function(aria){
      console.log(aria)
    })
  });
});
then-then-block-resolve-protractor-promise

The aria-label is used for accessibility purpose

Oh My God , what happens when there is an exception with above syntax.

Damn, that is the problem, whether there is an error or not the last then block will be executed.

Control using if block

So lets create flag in our test that when there is error we should set the flag to false, with which we can control using the if block


import { browser, element, by } from "protractor";
describe("Errors in Protractor",function(){
  
  browser.ignoreSynchronization = true; // for non-angular websites
  it("Error handling in protractor",function(){
  
    browser.get("https://google.com")
    let flag = true
    element(by.name("btnIii")).getAttribute("aria-label")
    .then(null, function(err){
      flag = false
      console.log("The error occured is : "+ err.name)
    })
    .then(function(aria){
      if(flag){
        console.log("****")
        console.log(aria)
      }//end of flag if block
    })
  });
})

Protractor Error Structure

WebDriverError :

WebDriverError is the top most error class in the protractor, it extends IError class IError class implements the Error interface from Typescript. All protractor Errors are subclasses of WebDriverError class.

then-then-block-resolve-protractor-promise

In this tutorial I have given a sample code which causes the error, that does not mean only this piece of code will raise error. Other commands also can raise errors

NoSuchElementError :

Protractor throws NoSuchElementError when there is no matching element present in the webpage.

Reasons : NoSuchElementError occurs because of one of the below reasons

  • Either Xpath you specified for the element is wrong.
  • The second reason is AJAX has not returned yet and you've already obtain NoSuchElementError
  • The page is still being rendered but you've already finished your element search because of low wait time.
  • The element is not on the page at all

Code which causes the NoSuchElementError :


									element(by.xpath("//label/span"))
									


Error Message:NoSuchElementError: No element found using locator: by(xpath, //label/span)
NoSuchWindowError :

Protractor throws NoSuchWindowError when user tries to switch to or perform an operation on browser windows when the window is not present.

Reasons : NoSuchWindowError occurs because of one of the below reasons

  • Current window closed
  • Target window is not opened yet, but you were trying to perform operation
  • When target window has been closed but still the code tried to perform operation on the target window.


Code which causes the NoSuchWindowError :


									browser.switchTo().window("window GuID");
									
NoSuchFrameError :

NoSuchFrameError happens when user tries to switch to a frame which is not present at the time.

Reasons : NoSuchFrameError occurs because of one of the below reasons

  • There is no frame with given details, or the details changed during the page loading time
  • Target Frame is not actually a frame, if the locators matches with exactly with another element( as first instance).
  • We have not given enough wait time to load the frame.


Code which causes the NoSuchFrameError :


									browser.switchTo().frame("frame1");
									
NoAlertPresentError :

Protractor throws NoAlertPresentError error when user tries to access a alert popup, which is currently not present.

Here Alert popup could be Alert Box, Confirmation Box, Prompt Box from the Javascript commands.

Reasons : NoAlertPresentError occurs because of one of the below reasons

  • When user tries to access alert, which is not present in the at current time
  • When javascript is blocked in the browser
  • Not giving enough time for the alert to load
  • When alerts are already closed


Code which causes the NoAlertPresentError :


									browser.switchTo().alert()
									
StaleElementReferenceError :

TimeoutError :

TimeoutError is related with explicitwait, fluentwait, pageLoadTimeOut, scriptLoadTimeout. Protractor throws the TimeoutError error when user has defined the wait time but the element have not been found within the wait time.

Reasons : TimeoutError occurs because of one of the below reasons

  • Element is not present or given Condition is not met
  • When the given timeout is very low
  • When page takes more time to load
  • When executeAsyncScript() takes more time to return its operation


Code which causes the TimeoutError :


									browser.get('https://chercher.tech/practice/explicit-wait-sample-selenium-webdriver.php');
									element(by.id("display-other-button")).click()
									let EC = ExpectedConditions;
									let condition = EC.visibilityOf(element(by.id("hidden")))
									browser.wait(condition, 30000)
									
ScreenshotError :

ScreenshotError error will be thrown when protractor fails to take screenshot of the webpage. If ScreenshotError occurs then the screenshot captured turns black

Reasons :

1. When we try to take screenshot in headless browser(phantomjs, htmlunitdriver) without enabling the screenshot functionality.


Code which causes the ScreenshotError :


									browser.takeScreenshot().then(function (png) {
										var stream = createWriteStream("exception.png");
										stream.write(new Buffer(png, 'base64'));
										stream.end();
									});
									
ScriptTimeoutError :

protractor throws ScriptTimeoutError error when executeAsyncScript takes more time than given time limit to return the value.

UnhandledAlertError :

protractor throws UnhandledAlertError error when user tries to perform while alert(javascript popup) is present on the page. Javascript pop ups will not allow to perform manual actions(manual testing) on the page when it is present on the page.
Reasons :

  • Javascript Popup is present on the page
  • You have written a code to accept the pop up automatically but still you are trying to handle the pop up.
  • You might missed code to handle the pop up.

Insight : User can use getAlertText method to get the text from the alert when UnhandledAlertError error occurs.

UnReachableBrowserError :

UnReachableBrowserError will be thrown when protractor is not able to connect to the browser after starting the browser.
Reasons :

  • Browser is taking more tome to invoke after the object creation
  • Browser died in between test execution, if you run large test suite.
  • Browser is not opened in virtual machines or in remote driver
  • The provided server address to RemoteWebDriver is invalid, so the connection could not be established.
  • Browser version and the driver server.exe / protractor version is not compatible
  • When you use IEdriver64.exe instead of IEdriver32.exe when the system is 32 bit architecture.
  • Note : IEDriver32.exe can be used in place of IEdriver64.exe but vice versa is not possible
NoSuchSessionError :

Protractor throws this error when protractor is not able to connect to the browser session, this error occurs mostly on Chromedriver
Reasons :

  • When the temp memory is running out of space, when ever we run on chrome, the chrome driver server occupies and leaves the cache file on temp directory
  • This error occurs when you run on Docker mostly ( We run our tests inside a docker container and the docker default dev/shm size is 64mb. Increasing this resolved the "no such session" issue for us. We use docker compose so just added shm_size: 256M to the docker-compose.yml file. )
  • Browser and Driver server.exe file version mismatch
  • Problem which appears when running tests for a prolonged period
MoveTargetOutOfBoundsError :

protractor throws MoveTargetOutOfBoundsError, when user tries to move/drag the element or the cursor outside the visible screen.
Reasons :

1. Change of screen size ( testcases are written in desktop but current execution is happening laptop, considering that desktop screen size is bigger)


Code which causes the MoveTargetOutOfBoundsError :


									let actions = browser.actions()
									actions.mouseMove( 10, 25 )
									actions.perform();
									
InvalidElementStateError :

Protractor throws InvalidElementStateError when user tries to perform operation on a Webelement whose state is disabled.

Subclasses of this Error gives detail explanations, the subclasses are ElementNotInteractableError, ElementNotSelectableError

Reasons :

1. When element state is disabled


Code which causes the InvalidElementStateError :


									<input type='button' disabled=true value='save'>
		
									// click the button which is disabled
									element(by.xpath("//input[@type='button']")).click();
									
ElementNotInteractableError :

ElementNotInteractableError is throws when we try to perform operation on an element which not intereactable at the moment. ElementNotInteractableError has two subclasses which are ElementNotVisibleError, ElementClickInterceptedError.
Reasons :

1. When element size is 0 x 0 (width =0 and height =0)


Code which causes the ElementNotInteractableError :


									<input type='button' height=0px width=0px value='save'>
		
									// click the button which has width=0 and height=0
									element(by.xpath("//input[@type='button']")).click();
									
ElementNotVisibleError :

Protractor throws ElementNotVisibleError when user tries to perform an operation on an web element, which is present in the page but the element is currently not visible.
Reasons :

1. Clicking a element which is not visible
2. sendkeys to element which is not visible
3. Element may not be visible because there are more elements under different pages, but those page source code is still present in cache.


Code which causes the ElementNotVisibleError :


									<input type='button' hidden=true value='save'>
		
									// click the button which is hidden (not visible)
									element(by.xpath("//input[@type='button']")).click();
									
ElementClickInterceptedError :

Indicates that a click could not be properly executed because the target element was obscured in some way, I never faced this error in my testing life.

UnSupportedCommandError :

Protractor has a methods, which gives a call to native methods present in the browser and browser reacts to the native commands. Recent times we have received updates for driver like geckodriver.exe and chromedriver.exe.

Some selenium commands are not supported by these driver and if we try to perform those commands using Protractor then those goes through the driver servers and Protractor throws UnSupportedCommandError if the driver server doesnot support the command
Examples : Gecko driver does not support Actions class

InvalidCoordinatesError :

Protractor throws InvalidCoordinatesError when user tries to move the mouse to a co-ordinate which is not valid using action class methods.
Reasons :

1. When we run our test in different size of monitors, we may face this issue.
ImeNotAvailableError :

Indicates that IME support is not available. This error is thrown for every IME-related method call if IME support is not available on the machine.

ImeActivationFailedError :

Indicates that activating an IME engine has failed.

ConnectionClosedError :

Protractor throws ConnectionClosedError when program tries to perform operation on safari browser but where safari browser is disconnected from the Protractor session.

ErrorHandler.UnknownServerError :

Error used as a place holder if the server returns an error without a stack trace.

InvalidCookieDomainError :

Protractor throws InvalidCookieDomainError when user attempts to add a cookie under a different domain (url) than the current URL.

JsonError :

Session capabilities normally returns the values in Json and Protractor parses it, JsonError occurs when user tries to get the session capabilities where the session is not created.

UnableToCreateProfileError :

We can open a browser with certain options using profiles, sometime new version of Protractor driverserver or browser version may not support the profiles, during such cases UnableToCreateProfileError raises.

UnableToSetCookieError :

Protractor throws UnableToSetCookieError when a driver fails to set a cookie.

Protractor Interview Questions

About Author

Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know. Knowledge is the only thing that doubles when you spend it.

I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Sachin
    Could you please add example for to handle an error like nosuchelement using promises.
     
    Reply