Right now I have this:
$error = new Error($id, $from, $to);
return $response
->withStatus(422)
->withHeader('Content-Type', 'text/html')
->write($error->error());
The Error
class returns this:
{"error":true,"code":422,"text":"Blah!"}
How can I set the error code in ->withStatus(422)
so it's set by the json string instead of by me manually?
Edit: I guess this could work:
$code = json_decode($error->error(), true);
$code = $code['code'];
/* ...blah blah code... */
->withStatus($code)
But I would like to know if there's a way to do it with less code.
Update the Error
class so that it has a code()
public method that returns just the 422
. You can now do:
$error = new Error($id, $from, $to);
return $response
->withStatus($error->code())
->withHeader('Content-Type', 'application/json')
->write($error->error());
Incidentally, as you're using JSON, if you make error()
return an array, you can do this:
$error = new Error($id, $from, $to);
return $response->withJson($error->error(), $error->code());