Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - Handling Constraint Failures

With SQLAlchemy, If I have a unique column in my database eg, username:

username = db.Column(db.String(50), unique=True)

When I add a row that breaks this constraint where the username I’m trying to add already exists, an IntegrityError is thrown:

IntegrityError: (IntegrityError) (1062, u"Duplicate entry 'test' for key 'username'")

Is it possible to instead map the breaking of a constraint to a custom exception? eg.UsernameExistsError

I want to be able to catch individual constraint breaks, and send a response back to the user. eg: "This username is already in use"

Is this possible? Or what would be the next best thing?

Any guidance would be greatly appreciated :)

like image 272
mickzer Avatar asked Jun 18 '15 21:06

mickzer


1 Answers

The next best thing might be surrounding the call with a try ... except, parsing the error message, and notifying the user with a constructed error message.

Along those lines, you could try ... except the error and return a custom error code with Flask's custom error pages.

like image 147
Celeo Avatar answered Oct 23 '22 00:10

Celeo