A Jev gate I inherited failed with Attempt to read property "answers" on null, three frames away from anything that mentioned TypeSafe. The real problem was a score question that had grown to eleven criteria over six months of tweaks. Jev had said so, clearly, in a 422 body that the client threw away.
The happy-path client handles one case: a 200 with answers in it. This is the rest of the surface — what the other status codes mean, which are worth a second attempt, and what the surrounding Laravel feature should do when the answer never arrives. The starting point is the thin Jev wrapper from batching Jev questions into one request.
Learn the two error shapes Jev returns#
Jev has two distinct failure bodies and they mean different things. A 422 Unprocessable Entity carries an HTTPValidationError: the body parsed fine, but the shape was wrong — a missing state, a score question with no criteria, a question map with nothing in it. Its detail is an array of validation errors. A 400 Bad Request carries an HTTPBadRequestError, and that means the body broke a request rule before validation ever got to your questions: invalid UTF-8, a byte order mark, more than 64 levels of nesting, a non-finite number, a malformed compressed body, or max_tokens_exceeded when the request is longer than the model's context. Its detail is a string or an object, never an array.
Here is a real 422 from a score question that collected one criterion too many:
{
"detail": [
{
"loc": ["body", "questions", "urgency", "score", "criteria"],
"msg": "List should have at most 10 items after validation, not 11",
"type": "too_long",
"input": "[\"Can wait\",\"Needs attention this week\",\"Needs atten…",
"ctx": { "field_type": "List", "max_length": 10, "actual_length": 11 }
}
]
}
The rest of the status codes are short and worth memorising, because three of them change what your retry policy should do:
| Status | What it means | Retry? |
|---|---|---|
400 |
Request rule broken, or max_tokens_exceeded |
No |
401 |
Missing or invalid API key | No |
413 |
Body over 32 MiB | No |
415 |
Unsupported Content-Encoding, or double compression |
No |
422 |
Body failed validation — a bad question | No |
429 |
Rate limited | Yes, with backoff |
529 |
TypeSafe temporarily overloaded | Yes, with backoff |
529 is the one people miss. It is not in the usual 5xx range a framework helper checks for, and it is the status you will see during a provider incident. The 400 with max_tokens_exceeded is the other one worth planning for: it means your state outgrew the model, which is a state design problem rather than an error handling one.
Turn a 422 loc path into a sentence#
The loc array is the whole value of a 422, and it is why you should never parse msg on its own. It is the path to the offending value: the request location first, then field names and array indices. ["body", "questions", "urgency", "score", "criteria"] says the urgency question, evaluated as a score, has bad criteria. Joined with dots and with the leading body dropped, it reads like a sentence a developer can act on without opening the payload.
Wrap that in an exception that carries the structured errors as well as the message, because the message is for humans and the array is for your metrics:
<?php
declare(strict_types=1);
namespace App\Support\Jev\Exceptions;
use RuntimeException;
final class JevValidationException extends RuntimeException
{
/** @param list<array{loc: list<string|int>, msg: string, type: string, input?: string, ctx?: array<string, mixed>}> $errors */
public function __construct(public readonly array $errors)
{
parent::__construct(
'Jev rejected the request: '.implode('; ', array_map(self::describe(...), $errors)),
);
}
/** @param array{loc: list<string|int>, msg: string, type: string} $error */
private static function describe(array $error): string
{
// Every request error starts with "body" — it carries no information.
$path = array_slice($error['loc'], 1);
// questions.urgency.score.criteria: List should have at most 10 items...
return implode('.', array_map(strval(...), $path)).': '.$error['msg'];
}
}
Keep the raw errors array on the exception. The type field (too_long, missing, string_type) is a machine-readable code, so a counter keyed by type tells you whether you are shipping malformed questions regularly or whether one deploy broke one question. Log the whole structure rather than the formatted string: both msg and input are bounded and may be shortened with an ellipsis, so string matching on them will eventually lie to you.
Four 422s account for almost everything you will hit in practice: a score question with more than ten criteria, an empty questions map, a choice question with no criteria key at all, and a box question or an assets block sent without the TypeSafe-Danger-Zone-Images: true header.
Retry only what can succeed#
A retry(3, 100) in front of a Jev call is worse than no retry. A 422 is deterministic — the same malformed question will be rejected three times, you will pay three round trips of latency to learn nothing, and the error your code finally sees is the third one rather than the first. Retry the things that can plausibly succeed on a second attempt: a connection reset, a read timeout, a 429, a 529, and genuine 5xx.
The mechanic that makes this readable in Laravel is easy to miss. When tries is greater than one, the HTTP client converts a failed response into an Illuminate\Http\Client\RequestException before your when callback runs, even if you never called ->throw(). So the callback can match on a status code rather than guess:
<?php
declare(strict_types=1);
namespace App\Support\Jev;
use App\Support\Jev\Exceptions\JevUnavailableException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
final readonly class Jev
{
private const string ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
public function __construct(
private string $apiKey,
private string $model = 'jev-latest',
private int $timeout = 8,
) {}
/** @param string|array<string, mixed> $state */
public function ask(string|array $state, QuestionSet $questions): Answers
{
$response = Http::withToken($this->apiKey)
->connectTimeout(2)
->timeout($this->timeout)
->retry(
times: 3,
sleepMilliseconds: self::backoff(...),
when: self::isTransient(...),
)
->post(self::ENDPOINT, [
'state' => $state,
'model' => $this->model,
'questions' => $questions->toPayload(),
]);
return new Answers($response->json('answers'), $response->json('usage'));
}
/** Exponential, with jitter so a fleet of workers doesn't retry in lockstep. */
private static function backoff(int $attempt): int
{
return (int) (250 * 2 ** ($attempt - 1)) + random_int(0, 150);
}
private static function isTransient(Throwable $e): bool
{
// A reset connection or a read timeout may well work next time.
if ($e instanceof ConnectionException) {
return true;
}
if (! $e instanceof RequestException) {
return false;
}
return match ($e->response->status()) {
429, 529 => true, // documented back-off cases
500, 502, 503, 504 => true,
default => false, // 400, 401, 413, 415, 422 — your bug
};
}
}
The jitter matters more than the exponent. Twenty queue workers that all take a 429 in the same second and all sleep exactly 250ms will hit the rate limit together again on the next attempt. If the call lives in a queued job, the backoff belongs at the job level as well — job middleware with rate limiting and backoff releases the job back to the queue instead of holding a worker in usleep() for two seconds.
One behaviour to know before you wire this up: once retries are configured, Laravel throws on a failed response whether you asked it to or not. Passing throw: false suppresses that for responses, but a connection failure still throws ConnectionException after the final attempt. There is no configuration in which a dead API gives you back a Response object.
Set timeouts the caller can actually wait for#
Laravel's defaults are 10 seconds to connect and 30 seconds to read. Jev answers in well under a second, so a client sitting on those defaults is not configured for Jev — it is configured for the worst outage the network can produce, and it will happily turn a "cheap screening question" into a thirty-second page load. Set the two independently, because they fail for different reasons: connectTimeout covers DNS and the TCP and TLS handshake, timeout covers the whole request.
Pick the budget from the caller, not from the API:
// config/services.php
'typesafe' => [
'key' => env('TYPESAFE_API_KEY'),
// In the request path: fail fast, the user is waiting.
'timeout' => (int) env('TYPESAFE_TIMEOUT', 8),
// In a queued job: a slow answer still beats no answer.
'queued_timeout' => (int) env('TYPESAFE_QUEUED_TIMEOUT', 25),
],
For a request-path gate, two seconds to connect and eight to read is generous for a model that normally answers in a few hundred milliseconds, and it bounds the worst case at roughly 30 seconds across three attempts plus backoff — which is still too long for a web request, so cap times at 2 there. In a queued job, where nobody is watching a spinner, give it the longer budget and let the retry policy do its work. The one number that must not surprise you is attempts multiplied by timeout plus total backoff; write it down and compare it against whatever the caller can actually wait for.
Decide whether the gate fails open or closed#
Once every retry is spent you have no answer, and the only remaining question is what the feature does without one. There is no general answer — it depends entirely on what the gate was protecting, and it is a product decision, not an infrastructure one.
A spam screen fails open. The cost of letting one spam message through for the twenty minutes of a provider incident is near zero; the cost of blocking every legitimate message is your support inbox:
public function allows(Message $message): bool
{
try {
return $this->jev->ask($message->body, $this->questions)->noul('is_spam') < 0.8;
} catch (JevUnavailableException $e) {
// Fail open: a slow afternoon at TypeSafe must not close the inbox.
report($e);
return true;
}
}
A verification check in front of a destructive action fails closed. If you cannot confirm the instruction is safe, you do not run it:
public function confirm(DeletionRequest $request): void
{
// No fallback and no catch — JevUnavailableException propagates and the
// action does not happen. Unverified is not the same as verified.
$confirmed = $this->jev->ask($request->toState(), $this->questions)
->noul('is_authorised');
throw_if($confirmed < 0.95, UnverifiedDeletionException::class);
}
Routing is the interesting middle case: fall back to the slow path rather than either extreme. If Jev was choosing a queue for a ticket, an outage should drop it into a human triage queue, not route it at random and not reject it. That is the same shape as the fallback in the Noul screen gate, where the screening question only ever decides whether to skip work, never whether work is allowed.
Map the API surface onto your own exceptions#
Callers should not import Illuminate\Http\Client\RequestException to decide whether to fall back. Collapse seven status codes into three exceptions that mean something in your domain: a bug in the request, a service that is unavailable, and an auth problem your operators need to fix now. The general pattern is in custom exceptions with render, report and context; this is the Jev-specific mapping.
/** @throws JevValidationException|JevRequestException|JevUnavailableException */
private function translate(Throwable $e): never
{
if ($e instanceof ConnectionException) {
throw new JevUnavailableException('Jev did not answer in time.', previous: $e);
}
if (! $e instanceof RequestException) {
throw $e;
}
$status = $e->response->status();
$detail = $e->response->json('detail');
throw match (true) {
// 422: detail is always a list of ValidationError.
$status === 422 => new JevValidationException(is_array($detail) ? $detail : []),
// 400: detail is a string or an object, never a list.
$status === 400 => new JevRequestException(self::flatten($detail), previous: $e),
$status === 401 => new JevAuthException('TypeSafe rejected the API key.', previous: $e),
$status >= 500, $status === 429 => new JevUnavailableException(
"Jev returned {$status} after every attempt.", previous: $e,
),
default => new JevRequestException("Unexpected Jev status {$status}.", previous: $e),
};
}
Wrap the post() call in try/catch (Throwable $e) { $this->translate($e); } and the public ask() method now has a documented three-exception surface. The split that matters to callers is JevUnavailableException — the only one of the three that is ever worth catching, because it is the only one a fallback can do anything about. Catching JevValidationException to fall back silently is how a broken question survives six months in production.
Render the failures through the exception handler#
The two exceptions that reach a controller deserve different HTTP responses, and Laravel 13 registers that in bootstrap/app.php rather than a handler class. An unavailable Jev is a 503 with a Retry-After header so clients back off properly; a validation failure is a 500, because it is your bug and should look like one on the dashboard.
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->render(function (JevUnavailableException $e, Request $request) {
return response()->json([
'message' => 'Automated checks are temporarily unavailable.',
], 503, ['Retry-After' => '30']);
});
// Never show a loc path to an end user — it describes your payload.
$exceptions->dontReport(JevUnavailableException::class);
})
dontReport on the unavailable case is deliberate. During a provider incident every request raises one, and a thousand identical Sentry events bury the one thing you want to see. Count them as a metric instead and report the validation exceptions, which are rare and always actionable.
Add the question names to every log line#
The failure that is genuinely hard to debug is the one where the exception is correct and you still cannot tell which call site produced it. Context::add() fixes that for the whole request or job: set the question names and the state size once, and every log line afterwards carries them, including the ones Laravel writes from inside the exception handler.
use Illuminate\Support\Facades\Context;
Context::add([
'jev.questions' => $questions->names(), // ['department', 'urgency', 'is_spam']
'jev.state_bytes' => strlen(json_encode($state)),
'jev.model' => $this->model,
]);
Log usage on the failure paths too, not just the successful ones. A 429 that arrives with a large recent input-token count is a quota problem; the same 429 on a small payload is a concurrency problem, and they have different fixes. The mechanics of carrying this context across a queue boundary are in request-scoped logging with Laravel Context — the values survive into the job, which is where most Jev calls end up living.
Test the unhappy path with Http::fake()#
Every branch above is testable without a network, and the sequence fake is what makes the retry policy verifiable rather than hopeful. Http::fakeSequence() returns responses in order, so a 429 followed by a 200 proves the retry happened and that the second answer is the one the caller receives.
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
it('retries a 429 and returns the second answer', function (): void {
Http::fakeSequence()
->push(['detail' => 'Rate limit exceeded.'], 429)
->push(['model' => 'jev-1.13.0', 'answers' => ['is_spam' => ['type' => 'noul', 'noul' => 0.02]], 'usage' => ['input_tokens' => 120, 'output_tokens' => 12]], 200);
expect(app(Jev::class)->ask('hello', $questions)->noul('is_spam'))->toBe(0.02);
Http::assertSentCount(2);
});
it('does not retry a 422 and names the offending question', function (): void {
Http::fake(['api.typesafe.ai/*' => Http::response([
'detail' => [[
'loc' => ['body', 'questions', 'urgency', 'score', 'criteria'],
'msg' => 'List should have at most 10 items after validation, not 11',
'type' => 'too_long',
]],
], 422)]);
expect(fn () => app(Jev::class)->ask('hello', $questions))
->toThrow(JevValidationException::class, 'questions.urgency.score.criteria');
// The important assertion: one attempt, not three.
Http::assertSentCount(1);
});
it('surfaces a connection failure as JevUnavailableException', function (): void {
Http::fake(['api.typesafe.ai/*' => Http::failedConnection()]);
expect(fn () => app(Jev::class)->ask('hello', $questions))
->toThrow(JevUnavailableException::class);
});
Http::assertSentCount(1) on the 422 test is the regression test for this whole article. The day someone "fixes" the flaky integration by adding a blanket retry(3, 100), that assertion fails and tells them why.
Avoid the five ways this bites in production#
Most of these cost me an afternoon each.
Retries turn a 422 into a throw you did not ask for. Adding retry() to a client that previously checked $response->failed() by hand changes the control flow: failed responses now raise RequestException because retryThrow defaults to true. Code downstream that expected a Response stops running.
Http::fake() returns 200 for anything you did not fake. A test that fakes only api.typesafe.ai/* and then hits a second host gets a silent empty 200, and your error handling test passes for the wrong reason. Assert the request count.
Sleeping in the request path is still blocking. retry() uses usleep(), so three attempts with exponential backoff holds a PHP-FPM worker for the full duration. In a web request, two attempts is the limit; anything more belongs in a job.
max_tokens_exceeded arrives as a 400, not a 413. The 413 is purely about the 32 MiB body limit. A state that is too long for the model's context comes back as a 400 with that code in detail, which is easy to mis-bucket as a malformed request and ignore.
Box questions and assets need an extra header. Sending assets or a box question without TypeSafe-Danger-Zone-Images: true is a 422 whose loc points at the question, not at the missing header — the one case where the path genuinely does not tell you the answer.
Wrapping Up#
Start with the retry predicate. If the client in front of you retries a 422, that is the change worth making today: a when callback that matches on 429, 529 and 5xx, and nothing else. Then set both timeouts from what the caller can wait for, and decide out loud whether each gate fails open or closed.
With the error surface handled, the next question is what to do with answers that arrive but are not confident enough to act on — which is choosing confidence thresholds from a labelled sample rather than from a round number. If you are still sending one request per question, batching them into a single call removes most of the 429s before you need the retry policy at all.
FAQ#
What do TypeSafe Jev 400 and 422 responses mean?
A 422 means the request body failed validation: a required field is missing, or a question is malformed — a score question with more than ten criteria, or a choice question with no criteria at all. Its detail is an array of validation errors, each pointing at the offending field. A 400 means the body broke a request rule before validation ran: invalid UTF-8, a byte order mark, more than 64 levels of nesting, a non-finite number, a malformed compressed body, or a request longer than the model's context length. Its detail is a string or an object, never an array.
How do I read the loc path in a Jev validation error?
The loc array is the path to the invalid value: the request location first, then field names and array indices. ["body", "questions", "urgency", "score", "criteria"] means the question you named urgency, which Jev read as a score question, has invalid criteria. Drop the leading body segment and join the rest with dots to get a path you can paste into a search of your own question definitions.
Should I retry a failed Jev request?
Only for 429, 529, genuine 5xx responses and connection faults. A 400 or a 422 is deterministic — the same request will be rejected every time, so retrying burns quota and adds latency without any chance of success. Retrying a 401 is worse, because an invalid key that is retried on every call across a fleet looks like an attack.
How do I set retries and backoff on Laravel's HTTP client?
Pass the attempt count, a closure that calculates the sleep in milliseconds, and a when callback that decides whether the failure is retryable. Because the HTTP client converts failed responses into a RequestException when more than one attempt is configured, the callback can inspect $e->response->status() directly and match on the status codes you consider transient. Add random jitter to the sleep so a fleet of workers does not retry in lockstep.
What should my app do when the Jev API is down?
Decide per gate, not globally. A screening question that only skips expensive work should fail open and let the work through, because the cost of a false negative during an outage is small. A verification check in front of a destructive or irreversible action must fail closed, because unverified is not the same as verified. A routing decision should usually fall back to a human queue rather than guessing, and in all three cases the fallback belongs behind your own JevUnavailableException rather than a caught RequestException.