Engineering · September 28, 2026
Read the Postgres error code, do not swallow it
A duplicate slug is not a server error. It is a 409, and Postgres already told you.
The lazy handler
INSERT fails, err != nil, return 500. The client sees "something went wrong", the log sees a unique violation, and the user retries the same thing three times.
The right handler
errors.As(err, &pgErr) — then pgErr.Code. 23505 is unique_violation: return 409 with a short lowercase message. 23503 is a foreign key: 422. Everything else is still 500, because everything else really is your problem.
Why not check first
SELECT then INSERT is a race. Two requests can both see "no row" and both insert. The constraint is the only thing that is actually atomic, so the constraint is the check — the code is how you read its answer.
Keep the message boring
{"error": "slug taken"}. Not the constraint name, not the table, nothing an attacker can map.