Should I check for DB constraints in code or should I catch exceptions thrown by DB

前端 未结 8 451
别跟我提以往
别跟我提以往 2021-02-04 03:43

I have an application that saves data into a table called Jobs. The Jobs table has a column called Name which has a UNIQUE constraint. The Name column is not PRIMARY KEY. I wond

8条回答
  •  遥遥无期
    2021-02-04 04:17

    The question that you need to answer is:

    "Do I need to present the user with nice messages". Example: There is already a Job with the name TestJob1. If the answer is No, just catch the error and present a common message If the answer is Yes, keep reading

    If you catch the error after the insert there isn't enough information to present the right message (at least in an agnostic DB way)

    On the other hand, there can be race conditions and you can have simultaneous transaction trying to insert the same data, therefore you need the DB constraint

    An approach that works well is:

    • check before to present a nice message
    • catch the exception and present a common error message (assuming this won't happen very frequently)

提交回复
热议问题