protractor icon indicating copy to clipboard operation
protractor copied to clipboard

How to handle element not found exception

Open mohit-excelindia opened this issue 12 years ago • 6 comments

Hi @juliemr @wlingke

Is there a way in Protractor to handle element not found exception, similar to what we can do in Java version of Selenium webdriver?

Thanks, Mohit

mohit-excelindia avatar Mar 21 '14 05:03 mohit-excelindia

Take at look at #543 - closing as dupe.

juliemr avatar Mar 21 '14 18:03 juliemr

@mohit-excelindia I saw your question in the linked issue posted by Julie.

This is how I do it:

// Use findAll syntax to avoid ElementNotFoundException
return $$('div.just-one-object').then(function (listWithJustOneThingInIt) {
    if (listWithJustOneThingInIt.length) {
        // Success
        var thingYouActuallyCareAbout = listWithJustOneThingInIt[0];
        return this.coolFunction(thingYouActuallyCareAbout);
    } else {
        // Please use custom exceptions
        this.CustomException.thro('lots of details about the state of the application.');
    }
});

Droogans avatar Apr 04 '14 19:04 Droogans

Hi @Droogans

Thanks for the code. Can you also share code of custom exception?

mohit-excelindia avatar Apr 04 '14 19:04 mohit-excelindia

https://github.com/Droogans/ProtractorPageObjects/tree/chapter-4#exceptions

I use a library called Astrolabe that includes this. Check out the whole thing for more info:

https://github.com/Droogans/ProtractorPageObjects/

Droogans avatar Apr 04 '14 19:04 Droogans

Hi @Droogans I could not find the custom Exception error handler code in the astrolabe. could you please add it over here in the comment.

ahmedusa avatar Aug 12 '16 19:08 ahmedusa

https://github.com/stuplum/astrolabe/blob/963eb5001d7d3ce019a6ed66cec62ba2bb0d316b/lib/astrolabe/base.js#L45

It simply hooks up to the exceptions npm module, which contains more information. Or, you can take a look at the example that uses this.exception on Astrolabe's readme.

However, keep in mind that the tutorial referenced above is very stale. I would not recommend making too many custom exceptions. Sometimes it's useful for invalid situations in your business logic, but overall, throw new Error() works just as well, without the extra dependency.

At some point I might redo it, since vanilla ES6 in node 6+ makes Astrolabe obsolete (it's just a fancy way to make very uniform looking es6 classes, with some URL convenience functions that are easy to reproduce). If I were to rewrite it today, it would be using at least protractor 4.0, with typescript featured prominently. That might make more sense once typescript releases 2.0.

Droogans avatar Aug 14 '16 21:08 Droogans