Skip to content

Commit 8cd350b

Browse files
author
heraclmene
committed
Add error handling example.
1 parent 2070a56 commit 8cd350b

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

examples/error-handling/main.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
6+
goselenium "github.com/bunsenapp/go-selenium"
7+
)
8+
9+
func main() {
10+
// Create the capabilities.
11+
capabilities := goselenium.Capabilities{}
12+
capabilities.SetBrowser(goselenium.FirefoxBrowser())
13+
14+
// Create the driver.
15+
driver, err := goselenium.NewSeleniumWebDriver("http://localhost:4444/wd/hub/", capabilities)
16+
if err != nil {
17+
fmt.Println("Error creating web driver.")
18+
return
19+
}
20+
21+
// Create the session.
22+
_, err = driver.CreateSession()
23+
if err != nil {
24+
fmt.Println("Error creating session.")
25+
return
26+
}
27+
28+
// Navigate to Google.
29+
_, err = driver.Go("https://www.google.com")
30+
if err != nil {
31+
fmt.Println("An error occurred whilst visiting URL.")
32+
return
33+
}
34+
35+
// Find a non existent element for it to error.
36+
_, err = driver.FindElement(goselenium.ByCSSSelector("mynonexistentelement"))
37+
if err != nil {
38+
// Switch the different types of errors. You do not need to do this in
39+
// every call and can simply abstract it behind a function. If you
40+
// don't want to handle the custom errors, they all implement the
41+
// Error interface meaning it'll work anywhere your normal errors do.
42+
switch err.(type) {
43+
case goselenium.CommunicationError:
44+
e := err.(goselenium.CommunicationError)
45+
// Switch the different states that we want to handle.
46+
switch e.Response.State {
47+
case goselenium.UnknownError:
48+
fmt.Println("An unknown error occurred.")
49+
case goselenium.SessionNotCreated:
50+
fmt.Println("The session was not created.")
51+
case goselenium.NoSuchElement:
52+
fmt.Println("Failed to find element. Example passed!")
53+
}
54+
case goselenium.UnmarshallingError:
55+
fmt.Println("An unmarshalling error occurred :<")
56+
}
57+
}
58+
59+
// Delete the session.
60+
driver.DeleteSession()
61+
}

0 commit comments

Comments
 (0)