feat(request): negotiate error response frmat based on Accept header
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user