'How to pass HTTP response to JSON?
I am working on a code base where controller have following lines of codes. The controller checks for exception and return JSON response if no error, otherwise throw exception error.
return $this->exception->tryCatch(
fn () => $this->json(
$this->customer->addUser()
)
);
public function tryCatch(callable $work): Response
{
try {
return $work();
} catch (Throwable $e) {
throw $exception;
}
}
But this always results 200 response. If I need different response(201), how can I adjust this code. I have been asked not to break the code structure. So asking here for any suggestion.
Solution 1:[1]
/**
* Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
*/
protected function json($data, int $status = 200, array $headers = [], array $context = []): JsonResponse
The second argument to the json
method takes the status of the response. By default it is 200, you can specify your own.
For example:
$this->json($this->customer->addUser(), 201);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |