Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/gatling/gatling.io-doc/llms.txt

Use this file to discover all available pages before exploring further.

Gatling’s Validation[T] type is a composable abstraction for operations that may either produce a value (Success[T]) or fail with an error message (Failure). It is used internally throughout the Gatling Scala SDK—most notably in Expression[T], which is defined as Session => Validation[T]—to propagate errors cleanly without throwing exceptions. Understanding Validation lets you write safe, composable Scala functions that chain multiple Session lookups and transformations, short-circuiting gracefully when any step fails.
This section is Scala-only. Java and Kotlin users work with plain functions and do not need to interact with Validation directly. JavaScript/TypeScript users can also skip this page.

The Two Cases

Validation[T] has exactly two implementations:
TypeMeaning
Success[T](value: T)The operation succeeded and produced a value of type T
Failure(message: String)The operation failed with a descriptive error message
The design mirrors Scala’s Either[String, T] or Try[T], but is intentionally simpler and more lightweight than Scalaz’s Validation.

Creating Instances

First, import the validation package:
import io.gatling.commons.validation._
You can construct instances directly using the case classes:
val ok: Validation[Int]     = Success(42)
val err: Validation[Int]    = Failure("something went wrong")
Or use the helper implicit conversions and factory methods:
// Implicitly lift a value into Success
val ok: Validation[Int] = 42.success
val err: Validation[Int] = "something went wrong".failure

Pattern Matching

The most direct way to handle a Validation result:
def describe(v: Validation[Int]): String = v match {
  case Success(n)   => s"Got value: $n"
  case Failure(msg) => s"Error: $msg"
}

Chaining with map and flatMap

The power of Validation comes from its monadic interface. Both methods propagate Failure automatically: if the original Validation is a Failure, the chained function is never called.

map — chain an operation that cannot fail

Use map when the next step always produces a value:
val result: Validation[String] =
  Success(42).map(n => s"The answer is $n")
// result == Success("The answer is 42")

val errResult: Validation[String] =
  Failure("upstream error").map(n => s"The answer is $n")
// errResult == Failure("upstream error")  — map was never called

flatMap — chain an operation that can also fail

Use flatMap when the next step itself returns a Validation:
def safeDivide(a: Int, b: Int): Validation[Int] =
  if (b == 0) Failure("division by zero") else Success(a / b)

val result = Success(10).flatMap(n => safeDivide(n, 2))
// result == Success(5)

val errResult = Success(10).flatMap(n => safeDivide(n, 0))
// errResult == Failure("division by zero")

Scala for-Comprehension

For chains of multiple flatMap/map calls, Scala’s for-comprehension syntax is cleaner. Think of it as a loop over a sequence of Validation steps that stops early on the first Failure:
val computation: Validation[String] =
  for {
    userId  <- session("userId").validate[String]
    groupId <- session("groupId").validate[String]
    page    <- session("page").validate[Int]
  } yield s"/groups/$groupId/users/$userId?page=$page"
This is exactly equivalent to:
session("userId").validate[String].flatMap { userId =>
  session("groupId").validate[String].flatMap { groupId =>
    session("page").validate[Int].map { page =>
      s"/groups/$groupId/users/$userId?page=$page"
    }
  }
}
If any step is a Failure, the entire for-block yields that Failure immediately.

Session Accessors and Validation

The Gatling Session API provides three levels of access for Scala users:
MethodReturn typeBehaviour on missing/wrong type
session("key").as[T]TThrows an exception
session("key").asOption[T]Option[T]Returns None
session("key").validate[T]Validation[T]Returns Failure(message)
For composable, safe code, prefer validate[T]:
val expr: Expression[String] = session =>
  for {
    raw   <- session("rawValue").validate[String]
    upper =  raw.toUpperCase
  } yield upper

Usage in Expression[T]

In Gatling Scala, Expression[T] is Session => Validation[T]. All SDK methods that accept a dynamic parameter will accept an Expression[T]. Scalar values are implicitly lifted to Success[T]:
// Scala — plain value is implicitly Success("static")
http("static url").get("/users")

// Scala — function returning Validation[String]
http("dynamic url").get(session =>
  session("userId").validate[String].map(id => s"/users/$id")
)
If your expression returns Failure, Gatling marks the request as failed with the failure message and does not execute the request.

Example: Composing Multiple Lookups

import io.gatling.commons.validation._
import io.gatling.core.Predef._

val buildPayload: Expression[String] = session =>
  for {
    name   <- session("name").validate[String]
    age    <- session("age").validate[Int]
    email  <- session("email").validate[String]
  } yield
    s"""{"name":"$name","age":$age,"email":"$email"}"""

http("create profile")
  .post("/profiles")
  .body(StringBody(buildPayload))
If "age" is missing from the Session, the request is skipped and Gatling logs a failure with the message produced by validate[Int]—no exception is thrown and no other virtual users are affected.

Build docs developers (and LLMs) love