0

I have a callback that is running for a specific post request. I am returning a certain JSON response at the end of it.

What if I want to catch errors inside one of the functions that are ran in that callback ? How do I get the Response object, or is there another way of sending a response immediately in case errors are catched ?

  private function someCalculation()
{

  try {

  } catch ($e) {
    //how to send response in case of error inside this function
    return new JsonResponse([
      'data' => null,
      'error' => $error
    ]);
  }
}

public function getTemplate(Request $request)
{


  $this->someCalculation();

  return new JsonResponse([
    'data' => $result,
  ]);

}

How do I send a JSON from inside the someCalculation function in case some errors are found ?

1 Answer 1

3

You can do it by checking is $this->someCalculation() is instance of JsonResponse. It is is we return the response, otherwise we set $result to the calculation result.

private function someCalculation() {
  try {
    // Something.
  } catch ($e) {
    return new JsonResponse([
      'data' => NULL,
      'error' => $e->getMessage(),
    ]);
  }
}

public function getTemplate(Request $request) {
  // Alternatively you can return an array with a status code and check on that instead.
  if ($this->someCalculation() instanceof JsonResponse) {
    return $this->someCalculation();
  }
  // If it didn't fail set set $result to the calculation result.
  $result = $this->someCalculation();

  return new JsonResponse([
    'data' => $result,
  ]);
}
4
  • But I'd rather send the response from inside someCalculation and not from the getTemplate function. Is it possible ?
    – Yaron
    Nov 28, 2019 at 9:38
  • @Yaron I have updated my answer.
    – user72672
    Nov 28, 2019 at 9:49
  • Thanks @Jdrupal but still this is not quite what I want. I want the calculation to return another value, but in case of an error then end and return a response to the user.. If I had the response object I would do something like $response->return($myresponse); but I don't think there's a way..
    – Yaron
    Nov 28, 2019 at 10:33
  • Please join me here, chat.stackexchange.com/rooms/101578/….
    – user72672
    Nov 28, 2019 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.