Raise Using Errcode And Hint

RAISE ... USING attaches a custom ERRCODE and HINT to a business error, letting callers catch the exact SQLSTATE instead of parsing message text.

SqlResilience

Code

snippet
-- RAISE ... USING 给业务错误挂上自定义 ERRCODE(5 字符 SQLSTATE)与 HINT,
-- 调用方按 SQLSTATE 精确捕获,不再解析消息文本猜错误类型
CREATE TABLE accounts (id int PRIMARY KEY, balance numeric NOT NULL);
INSERT INTO accounts VALUES (1, 100.00);

CREATE OR REPLACE FUNCTION withdraw(acct_id int, amount numeric)
RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
    IF amount <= 0 THEN
        RAISE EXCEPTION 'amount must be positive, got %', amount
            USING ERRCODE = 'CH001',
                  HINT = 'check the request body';
    END IF;
    UPDATE accounts SET balance = balance - amount WHERE id = acct_id;
    IF NOT FOUND THEN
        RAISE EXCEPTION 'account % not found', acct_id
            USING ERRCODE = 'CH002';
    END IF;
END;
$$;

DO $$
BEGIN
    PERFORM withdraw(1, -5.00);
EXCEPTION
    WHEN sqlstate 'CH001' THEN
        RAISE NOTICE 'CH001 rejected: %', SQLERRM;
END $$;

SELECT withdraw(1, 10.00);   -- 正常路径扣款
SELECT balance FROM accounts WHERE id = 1;

DROP FUNCTION withdraw;
DROP TABLE accounts;

How execution unfolds

SELECT / INSERT / UPDATE / CREATE statements share the script, touching accounts.

Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Putting it to use

Run the statement against the accounts table.

Core lines

SELECT balance FROM accounts WHERE id = 1;
CREATE TABLE accounts (id int PRIMARY KEY, balance numeric NOT NULL);
INSERT INTO accounts VALUES (1, 100.00);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`accounts` — referenced directly, no join needed.