Errors in Protractor

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

In Typescript/JavaScript, we don't have Exception, we call it as an error. Without a doubt, Error stops the execution, but we are more powerful than the 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 the 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 happen 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 the 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, the 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 the 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 the 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 the catch block, the user should mention what is the error that we should handle because we cannot handle all the error as a different error will require different code to handle the situation.

The Catch block will not be executed if there is no error occurs in the 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 an 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 an error 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 the 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 a try block
When finally block will not execute :

  • When System.exit() code occurs in try or in the catch block
  • When JVM crashes
  • When try block is executed infinitely without breaking
  • When the 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")
										}
									});
									

Read JSON using require


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 exist alone
  • catch or finally or both should follow try block
  • The catch block is optional when finally block is present
  • The finally block is optional when catch block is present
  • There is no block which executes when an error has not occurred in typescript ( but exists in python language)
  • We can't have the 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 the program without stopping the execution whenever there is an exception

addCookie in Protractor

Multiple catch blocks with try block

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

The Compiler decides to which catch block should be executed if the exception mentioned in the 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 an 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 the 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 an 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.


An 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 the 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.

Handle PopUps in Protractor

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 an 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 a throw statement.

Below program throws an 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 don'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 the 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 the wrong way.

The Value selected or not in a dropdown

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 the 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 did not 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 errors in the protractor are promises containing errors.

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

The syntax for handling protractor errors: protractor-error-handling-asynchonous-error

In the 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 the right way like if the 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 the 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 the 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 let's create a flag in our test that when there is an 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
    })
  });
})

POST API Method

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 an error. Other commands also can raise errors

NoSuchElementError :

Protractor throws NoSuchElementError when there is no matching element present on 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 obtained 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 a 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
  • The Target window is not opened yet, but you were trying to perform the operation
  • When the target window has been closed but still the code tried to perform an 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 locator matches with exactly with another element( as the 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 a user tries to access alert, which is not present in the at the 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()
									

Properties file

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 the 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)
									

Pre-Install & Post-install in Package Json

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 a screenshot in the 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 a user tries to perform while alert(javascript popup) is present on the page. Javascript pop ups will not allow performing 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 to code to handle the pop up.

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

Spec files in POM

UnReachableBrowserError :

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

  • Browser is taking more time to invoke after the object creation
  • Browser died in between test execution if you run the 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, whenever we run on chrome, the chrome driver server occupies and leaves the cache file on the 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
  • The Problem which appears when running tests for a prolonged period
MoveTargetOutOfBoundsError :

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

1. Change of screen size ( test cases 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();
									

What is Docker ?

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 an element which is not visible
2. sendkeys to element which is not visible
3. The Element may not be visible because there are more elements under different pages, but those pages source code is still present in the 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 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 a driver like geckodriver.exe and chromedriver.exe.

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

InvalidCoordinatesError :

Protractor throws InvalidCoordinatesError when the 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.

Protractor with Docker

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 a program tries to perform an 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 return the values in JSON and Protractor parses it, JsonError occurs when the 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

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Gowtham
    How to solve this error?
    
    
    
    Message:
        Failed: element not interactable
          (Session info: chrome=77.0.3865.90)
        Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
    
    
    Code:
    var ele = element(by.xpath("//*[@id='projectname']/div/div/md-input-container"));
            ele.sendKeys("Sample New Project");
    Reply
  • Sachin
    Could you please add example for to handle an error like nosuchelement using promises.
     
    Reply