No, Yii2 itself does not provide a specific RuntimeException class.
Instead, Yii2 typically relies on PHP's built-in exceptions like \RuntimeException, \InvalidArgumentException, etc., or Yii's own exceptions like yii\base\Exception or yii\base\InvalidParamException.
What to use in Yii2 when you want a runtime exception?
Use PHP’s built-in:
php
throw new \RuntimeException('Your error message here');
or if you want to use Yii exceptions:
php
use yii\base\Exception;
throw new Exception('Your error message here');
Summary:
Yii2 has its own base Exception class (yii\base\Exception) and some others.
You're correct in your reasoning and the dilemma you're facing:
In your original code, if $nonce is null at the time generateInteractionToken() is called, JwtHelper::generateInteractionToken() throws a TypeError because it expects a string, not null.
To avoid this, you added regeneration of the nonce if it's null, but this effectively breaks the protection against bots that have no valid nonce stored — you're silently "forgiving" the missing nonce and generating a new one, thereby allowing a possible bot to get a valid token.
Why the nonce could be null at token generation:
The nonce is normally set during controller event EVENT_BEFORE_ACTION triggered generateNonce(). This means before any action, the session should normally have the nonce.
Your token generation call (perhaps from a view or AJAX) expects the nonce to be present.
But if the client has no prior session with a nonce (e.g., first request, or a new client without cookies or session persistence), it will not be set yet.
Or due to some session expiration or reset, nonce may also be missing.
Understanding the original intent of the nonce and token
The nonce is a secret value stored in the user's session to tie the token to that specific session. It's a way to prevent replay attacks and CSRF.
If the token is generated without the nonce in the session, then it's logically invalid or it can be trivially guessed or replayed.
How to fix this properly without defeating the purpose:
1. Ensure generateNonce() is called before generateInteractionToken()
The nonce must be created before token generation is attempted.
You currently attach generateNonce() to Controller::EVENT_BEFORE_ACTION. But if generateInteractionToken() is called in a context where this event hasn't fired or session hasn't been started yet (for example, during view rendering before the action runs), the nonce might still be missing.
Solution: Make sure to call or ensure that generateNonce() has been invoked first (maybe eagerly during behavior initialization, or on demand before generating the token).
Example:
php
public function generateInteractionToken(): string
{
if (!$this->getSession()->has($this->sessionKey)) {
$this->generateNonce();
}
$nonce = $this->getSession()->get($this->sessionKey);
// nonce should no longer be null here
$issuedAt = time();
return JwtHelper::generateInteractionToken($nonce, $issuedAt);
}
This way you only generate the nonce once and explicitly if missing, keeping token generation semantics strict.
2. Fail early if nonce is not present rather than silently generating
If your business logic demands that the nonce be created only at the EVENT_BEFORE_ACTION and never regenerated silently, you can throw an exception in generateInteractionToken() if no nonce is found:
php
public function generateInteractionToken(): string
{
$nonce = $this->getSession()->get($this->sessionKey);
if ($nonce === null) {
throw new \RuntimeException('Nonce is missing in session. Cannot generate interaction token.');
}
$issuedAt = time();
return JwtHelper::generateInteractionToken($nonce, $issuedAt);
}
Then you fix your code or usage so the nonce always exists before this call or handle the exception.
3. Check your request flow
Confirm that session is started and nonce is generated before rendering views or JS injection.
If generating the token for a JS snippet on a page, ensure it's done after the nonce generation step.
Possibly debug when sessions are created and destroyed to avoid nonce loss.
Summary of recommendations
Option
Pros
Cons
Regenerate nonce silently
No fatal errors, token always valid
Undermines security, allows bots easily
Throw exception if nonce missing
Fail fast, easier to debug
Might require refactoring how/when nonce is created
Check and generate nonce on demand
Safe, nonce always present when needed
Slightly different flow, may cause unexpected side effects, but better control
Code snippet with on-demand nonce generation (recommended):
php
public function generateInteractionToken(): string
{
if (!$this->getSession()->has($this->sessionKey)) {
$this->generateNonce();
}
$nonce = $this->getSession()->get($this->sessionKey);
if ($nonce === null) { // sanity check
throw new \RuntimeException('Nonce is null after generation.');
}
$issuedAt = time();
return JwtHelper::generateInteractionToken($nonce, $issuedAt);
}
Check that your session manager works well and session is started
Sometimes session not starting causes this problem.
Verify session storage (SessionManager) works as expected.
Final note on your JS code and the token
Your JS inserts the user_interaction_token only after user interaction or a fallback delay.
If the token is generated before nonce exists, token is invalid.
This emphasizes the importance of nonce existence before token generation.
TL;DR
Your original code error occurs because token generation is called before nonce is set. You shouldn't silently generate a new nonce on token generation because that breaks security assumptions. Instead, ensure the nonce is created beforehand (e.g., call generateNonce() explicitly if missing) or throw an exception. This way, token generation does not get invalid data and security assumptions hold.
But for runtime exceptions, the canonical approach is to use PHP's native \RuntimeException.
Yii2's exception hierarchy mostly extends from PHP's SPL exceptions, so mixing them is fine.
Example in your case
php
public function generateInteractionToken(): string
{
$nonce = $this->getSession()->get($this->sessionKey);
if ($nonce === null) {
throw new \RuntimeException('Nonce is missing in session. Cannot generate interaction token.');
}
$issuedAt = time();
return JwtHelper::generateInteractionToken($nonce, $issuedAt);
}