Is this safe to do?
This is not unsafe. Although by doing this you’ve created a coupling between your application and the database(MySQL). What if down the road you decide to replace MySQL with some other database solution? The error codes will be changed, and your code will raise inconsistent messages.
If so, why isn’t this implemented at a lower level?
Probably for the same concern I am having.