How can I return a JSON response from an internal function ? (not the main callback) 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' =&gt; null,
      'error' =&gt; $error
    ]);
  }
}

public function getTemplate(Request $request)
{


  $this-&gt;someCalculation();

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

}


How do I send a JSON from inside the someCalculation function in case some errors are found ?
You can do it by checking is $this-&gt;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' =&gt; NULL,
      'error' =&gt; $e-&gt;getMessage(),
    ]);
  }
}

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

  return new JsonResponse([
    'data' =&gt; $result,
  ]);
}