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 a 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):
Protractor errors are asynchronous Errors ones, so you can skip to protractor errors if you want.
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 :
interface Error {
name: string;
message: string;
}
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 that is not present in our local system, etc..
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 have 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
}
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 have 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);
}
});
});
The 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 :
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")
}
});
});
In the below program, the code present in try block will not throw an 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")
}
});
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 a 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")
}
});
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'
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 the 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 the 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 the 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 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.
The 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');
}
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")
}
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:
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 the 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 returns nothing but How would I work with function which returns 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)
})
});
});
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.
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
})
});
})
WebDriverError is the topmost 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.
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
Protractor throws NoSuchElementError when there is no matching element present on the webpage.
Reasons : NoSuchElementError occurs because of one of the below reasons
Code which causes the NoSuchElementError :
element(by.xpath("//label/span"))
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
Code which causes the NoSuchWindowError :
browser.switchTo().window("window GuID");
NoSuchFrameError happens when a user tries to switch to a frame that is not present at the time.
Reasons : NoSuchFrameError occurs because of one of the below reasons
Code which causes the NoSuchFrameError :
browser.switchTo().frame("frame1");
Protractor throws NoAlertPresentError error when a user tries to access an 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
Code which causes the NoAlertPresentError :
browser.switchTo().alert()
TimeoutError is related with explicitwait, fluentwait, pageLoadTimeOut, scriptLoadTimeout. The protractor throws the TimeoutError error when the user has defined the wait time, but the elements has not been found within the wait time.
Reasons : TimeoutError occurs because of one of the below reasons
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 error will be thrown when protractor fails to take a 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();
});
protractor throws ScriptTimeoutError error when executeAsyncScript takes more time than given time limit to return the value.
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 :
Insight : User can use getAlertText method to get the text from the alert when UnhandledAlertError error occurs.
UnReachableBrowserError will be thrown when protractor is not able to connect to the browser after starting the browser.
Reasons :
Protractor throws this error when protractor is not able to connect to the browser session, this error occurs mostly on Chromedriver
Reasons :
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();
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 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();
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();
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.
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
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.
It 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.
This indicates that activating an IME engine has failed.
The protractor throws ConnectionClosedError when a program tries to perform an operation on the safari browser but where the safari browser is disconnected from the Protractor session.
Error used as a place holder if the server returns an error without a stack trace.
Protractor throws InvalidCookieDomainError when a user attempts to add a cookie under a different domain (URL) than the current URL.
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.
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.
Protractor throws UnableToSetCookieError when a driver fails to set a cookie.
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");