# Retrying a code block on 401

**URL:** <https://community.gatling.io/t/retrying-a-code-block-on-401/6227>\
**Category:** Gatling (Open-Source)\
**Created:** [August 24, 2021, 12:55pm UTC](https://community.gatling.io/t/retrying-a-code-block-on-401/6227 "2021-08-24T12:55:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Wajih\_A](https://avatars.discourse-cdn.com/v4/letter/w/b487fb/32.png) [@Wajih\_A](https://community.gatling.io/u/Wajih_A)\
**Post date:** [August 24, 2021, 12:55pm UTC](https://community.gatling.io/t/retrying-a-code-block-on-401/6227/1 "2021-08-24T12:55:20Z")

</div>

I have this in lib.scala  
def authenticate(username: String, password: String): ChainBuilder = {  
exec(flushCookieJar)  
.exec(http(“test”)  
.post(AuthnEndpoint)  
.disableUrlEncoding  
.headers(getXAuthHeaders(username, password))  
.check(status.in(200,401)).saveAs(“auth\_resp\_code”)  
.check(jsonPath("$.tokenId").find.saveAs(“token”)))  
}

And this in run.scala  
exec(lib.authenticate("${username}", userPassword )  
.doIf(session =\> session(“auth\_resp\_code”).as[Int] == 401)) {  
exec(lib.authenticate("${username}", userPassword))  
}

I want to retry authenticate() if it fails for the first time with a 401. Furthermore i don’t want the 401 to be counted towards a KO.

Is this the correct approach?

And in the “doIf” block is there a way from me to see if it is being executed. How could i do something like println(“i am here”)

Regards,

---

<div class="post-metadata">

**Author:** ![Wajih\_A](https://avatars.discourse-cdn.com/v4/letter/w/b487fb/32.png) [@Wajih\_A](https://community.gatling.io/u/Wajih_A)\
**Post date:** [August 24, 2021, 4:40pm UTC](https://community.gatling.io/t/retrying-a-code-block-on-401/6227/2 "2021-08-24T16:40:56Z")

</div>

No need to reply…this works quite nicely 🙂
