Repeating exceptions under different names? What is the standard practice?

I currently have this client code in my PHP MVC web application:

try { BookMapper::insert($book); } catch (DbUniqueConstraintViolationException $e) { $errorList->addMessage($book . " already exists!"); } 

I am wondering if it is not bad to use links to low-level Db * frameworks for my client code? If so, should I change my model code as follows:

 class BookAlreadyExistsException extends Exception { } class BookMapper { public static function insert($book) { try { // call to DB-layer to insert $book // (not relevant to the question) } catch (DbUniqueConstraintViolationException $e) { throw new BookAlreadyExistsException(); } } } 

and then use this new client code ...

 try { BookMapper::insert($book); } catch (BookAlreadyExistsException $e) { $errorList->addMessage($book . " already exists!"); } 

Or something else? Or is it an original method?

Thanks!

EDIT: I just want to add, the last method reads the best IMO, but it is related to the creation / reorganization of the object and, more importantly, it requires duplication of the reorganization code in each mapper insert () method. The first method is easy to implement and catch and works for any model, but I remember reading somewhere that you should not do this?

+4
source share
2 answers

I think you should definitely throw your own exception.

But I would also consider the third option, and this allows the insert method to return true for success and false for failure. Exceptions should be used for exceptions, and the fact that the book already exists can be a really expected / predicted case.

And if duplicate books are indeed exceptions that may not be possible (if only for programming errors), then you can also stick to the database exception, but in this case do not catch it. Let it bubble to the end.

+2
source

I highly recommend this article . Although it is written for Java, these principles apply to PHP as well. It has good recommendations on what types of exceptions you should throw and catch.

+1
source

All Articles