0

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.

Newwt
  • 491
  • 1
  • 5
  • 22
  • 1
    this is the prober way, withStatus accepts an integer parameter, and the $status property has an int type, and unfortunately `write` method does not update the error status/headers – hassan Apr 28 '17 at 12:34

1 Answers1

1

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());
Rob Allen
  • 12,643
  • 1
  • 40
  • 49
  • This is EXACTLY how I fixed it a few days ago, except the array part. Thank you very much! (btw did I just get my question answered by THE rob allen?) – Newwt May 04 '17 at 06:36
  • 1
    Not sure about THE Rob Allen, but I'm @akrabat on Twitter… – Rob Allen May 04 '17 at 06:50