Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Symfony controller which basically checks if requested parameters are in the request, then passes these parameters to a service. The service use Guzzle to call an API, does some things with the result and then passes it back to the controller in order to display a Json with the response.

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

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

Solution 2: Should I throw an Exception in the service, catch it in my controller and use the $this->get("Logger") in the controller in order to log the error in log files

like image 525
iBadGamer Avatar asked Feb 02 '17 09:02

iBadGamer


1 Answers

It would be nice if your core logic is itself in a service and not in your controller.

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

// 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;
}

Consider also a Solution 3: Throw an exception in a service and catch it in a custom exception listener, where you can log it and take further action (like replacing the Response object, etc.).

like image 79
Ivan Kvasnica Avatar answered Nov 03 '22 22:11

Ivan Kvasnica