Where to log database errors in MVC Architecture

Or any infrastructure for that matter.

Using Zend Framework 2 as an example, I have the following table class:

<?php namespace Contact\Model; use Zend\Db\TableGateway\TableGateway; use Zend\Db\TableGateway\AbstractTableGateway; use Zend\Log\Logger; class UserContactsTable extends AbstractTableGateway { protected $tableGateway; /** * * @var \Zend\Log\Logger Instance */ protected $logger; public function __construct(TableGateway $tableGateway, Logger $logger ) { $this->tableGateway = $tableGateway; $this->logger = $logger; } /** * Save a contact * * @param \Sms\Model\UserContact $userContact */ public function saveUserContact(UserContact $userContact) { $data = array( 'user_id' => $userContact->user_id, 'contact_id' => $userContact->contact_id ); try { $this->tableGateway->insert($data); } catch (\Exception $e) { //log $this->logger->crit($omeErrMsg); } } } ?> 

Do I have to register here? Should I associate my logger with a table class? Should I let saveUserContact function throw an exception if the insert fails and gets caught in the controller and logs there?

What are the best practices?

My initial idea was to create a class with some persistent error messages, such as insert and update errors, which the registrar will use in the table class, but I'm not sure if this is the right process.

Actually this is not limited to PHP or Zend Framework 2, but it happens that this is the language that I use.

+4
source share
2 answers

I would consider that the individual components of the system should be as decoupled as possible. Thus, in this example, if saveUserContact fails, then this should probably throw an exception, because this is not the expected behavior. This class should not be aware of what will happen "further down the chain", for example, error reporting.

As you already mentioned, it would be better to throw an exception and catch it in your controller (or, perhaps, in some other form of listener), which will then process the logging.

The advantage of this approach is that your system will be much easier to test, because you will have fewer objects to stub when constructing a UserContactsTable (mock) object for testing.

+5
source

I usually feel that you should log failures where they occur (unless they are expected, in which case it is noisy), but propagate the exception to the stack (or the shell exception), so the caller may decide to ignore / retry / fail (and register your own message, which is more important for business logic).

+2
source

All Articles