feat(request): negotiate error response frmat based on Accept header

This commit is contained in:
kj
2026-09-03 18:23:42 -03:00
parent ee0db0307e
commit 2ae9ef39f3

View File

@@ -157,6 +157,10 @@ class Request extends Neuron
/**
* Function to execute when an invalid value has been detected.
*
* Always answers with a single error and HTTP 422. The representation is
* negotiated from the request's Accept header: JSON when the client asks
* for application/json, plain text otherwise.
*
* @param string $error
*
* @return void
@@ -164,6 +168,16 @@ class Request extends Neuron
public function onInvalid(string $error): void
{
http_response_code(422);
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
if (str_contains($accept, 'application/json')) {
header('Content-Type: application/json');
print(json_encode(['error' => $error]));
return;
}
print($error);
}
}