diff --git a/src/Libs/Request.php b/src/Libs/Request.php index 122ceab..c82ec00 100644 --- a/src/Libs/Request.php +++ b/src/Libs/Request.php @@ -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); } }