Checking for integry constraint violation before insert

I am adding new users to this table:




create table users (

    username char(15) primary key,

    fullname char(40) not null,

    email char(40) unique not null,

    password char(32) not null,

    created datetime not null,

    expires datetime default null,

    lastlogin datetime default null,

    activated datetime default null

)



When a new user is added with a username or emailaddress that already is taken by a user, then I get this error message:


CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test@hotmail.com' for key 3INSERT INTO `users` (`username`, `fullname`, `email`, `password`, `created`) VALUES (:yp0, :yp1, :yp2, :yp3, NOW())

Is there a way to catch the exception and handle the error (give user feedback in register form if it was email or username that was wrong), or should I make two queries before inserting the data to check if the username and email address is not taken?

There is an "unique" validator.

Check the section "Declaring validation rules" in the guide:

Creating Model - Section of the Guide

How to procceed when unique key is not only one db field?

write your own validation rule