Should I log errors in the controller or in the service?

I have a Symfony controller that basically checks to see if the requested parameters are in the request, then passes those parameters to the service. The service uses Guzzle to call the API, performs some actions with the result, and then passes it back to the controller to display Json with the response.

I have a noob question about error handling, if Api I call with Guzzle return an error, what is the best solution?

Solution 1: Should I log an error using the Logger service introduced in my own service and return an error to my controller in order to display it.

Solution 2. If I have to throw an exception in the service, catch it in my controller and use $ this-> get ("Logger") in the controller to log the error in the log files.

+4
source share
1 answer

It would be nice if your main logic itself was in the service, and not in your controller .

That way, you can use the try-catch block inside the service, where you call another service, and your controller stays clean and tidy - you just call the service without catching any exceptions.

// AppBundle/src/Controller/MainController.php
public function mainAction()
{
  // ...
  $result = $this->get('my_service')->getResult($parameters);
  if (!$result) {
    // show an error message, pass it to another service, ignore it or whatever you like
  }
}

// AppBundle/src/Service/MyService.php
public function getResult($parameters)
{
  try {
    $apiResult = $this->apiService->get($parameters);
  } catch (ApiException $e)
    $this->logger->error('My error message');
    $apiResult = null;
  }

  return $apiResult;
}

3: , (, Response ..).

+1

Source: https://habr.com/ru/post/1668605/


All Articles