How to gracefully catch a yii\db\IntegrityException

Hi there,

I have a table in my database called service_orders that has an autoincrement primary key, but that has a separate UNIQUE field called SVONumber.

In the CREATE form for a service order, a user has to manually enter the SVONumber, and when they choose to save the record, if they enter a duplicate SVONumber (or one that has already been added to another record), the system rightfully send an exception, namely yii\db\IntegrityException

I was able to catch the expection using:

try { 


} catch (\Exception $e) {

   Yii::warning("Oops, it looks like you may have tried to use an SVO number that has already been added to the database.");


I initially tried:

catch (yii\db\IntegrityException $e)

but that failed to catch the exception. So I went with the general PHP \Exception, even though this is more of a catch all.

So now that I am catching the exception, what I need to do is display a warning to the user that shows up in some kind of a dialog, and I need the application to NOT try to route to another page or display the standard Yii page that shows the exception and the raw PHP code. I need to basically just keep the user on the page, so they can change the SVO number in the form and try to save it again, without having to re-enter all the other fields in the form.

I am at a loss on how to do this and would really appreciate some help / suggestions.

Many thanks in advance.


Why don’t you use unique validator on SVONumber?