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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What objects does the SQL involve?
- `accounts` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.