Is there way to give user-friendly error message on constraint violation

后端 未结 4 1428
梦毁少年i
梦毁少年i 2020-12-20 13:37

Say I have column Gender and constraint CHECK( Gender IN (\'F\', \'M\', \'OTHER\')).
If I accidentally forgot to handle this on client side, us

4条回答
  •  一整个雨季
    2020-12-20 14:00

    If you are looking for a way to tell Oracle always to replace the exception message "ORA-02290: check constraint (SYS_C099871244) violated" by another message like "ORA-20001: Gender must be F or M", then the answer is: no, it can't be done.

    What you can do is provide a solution that can be used by developers in their code something like this:

    ...
    begin
        insert into emp (empno, gender) values (p_empno, p_gender);
    exception
        when others then
           error_pkg.handle_exception;
    end;
    

    The error_pkg.handle_exception procedure would parse the Oracle exception message and extract the name of the constraint (if it was a constraint violation) and lookup that constraint name in a cross reference table to get the required message, then use raise_application_error to re-raise the exception with the new message.

    I suppose Oracle could offer a package and table like this as standard, but perhaps since in practice there are many different requirements for error handling in system, it isn't considered to be generally useful enough.

提交回复
热议问题