And*_*rew 5 postgresql stored-procedures plpgsql stored-functions
我正在努力弄清楚如何最好地处理从 Postgres 存储函数返回到我的应用程序的结果或错误。
考虑以下人为的伪代码示例:
app.get_resource(_username text)
RETURNS <???>
BEGIN
IF ([ ..user exists.. ] = FALSE) THEN
RETURN 'ERR_USER_NOT_FOUND';
END IF;
IF ([ ..user has permission.. ] = FALSE) THEN
RETURN 'ERR_NO_PERMISSION';
END IF;
-- Return the full user object.
RETURN QUERY( SELECT 1
FROM app.resources
WHERE app.resources.owner = _username);
END
Run Code Online (Sandbox Code Playgroud)
该函数可能因特定错误而失败,也可能成功并返回 0 个或更多资源。
首先,我尝试创建一个自定义类型以始终用作每个函数中的标准返回类型:
CREATE TYPE app.appresult AS (
success boolean,
error text,
result anyelement
);
Run Code Online (Sandbox Code Playgroud)
然而 Postgres 不允许这样做:
[42P16] ERROR: column "result" has pseudo-type anyelement
Run Code Online (Sandbox Code Playgroud)
然后我发现了 OUT 参数并尝试了以下用途:
CREATE OR REPLACE FUNCTION app.get_resource(
IN _username text,
OUT _result app.appresult -- Custom type
-- {success bool, error text}
)
RETURNS SETOF record
AS
$$
BEGIN
IF 1 = 1 THEN -- just a test
_result.success = false;
_result.error = 'ERROR_ERROR';
RETURN NULL;
END IF;
RETURN QUERY(SELECT * FROM app.resources);
END;
$$
LANGUAGE 'plpgsql' VOLATILE;
Run Code Online (Sandbox Code Playgroud)
Postgres 也不喜欢这样:
[42P13] ERROR: function result type must be app.appresult because of OUT parameters
Run Code Online (Sandbox Code Playgroud)
还尝试了类似的功能,但相反:返回自定义 app.appresult 对象并将 OUT 参数设置为“SETOF RECORD”。这也是不允许的。
最后我研究了 Postgres 异常处理使用
RAISE EXCEPTION 'ERR_MY_ERROR';
Run Code Online (Sandbox Code Playgroud)
因此,在示例函数中,我只是提出此错误并返回。这导致驱动程序发回错误:
"ERROR: ERR_MY_ERROR\nCONTEXT: PL/pgSQL function app.test(text) line 6 at RAISE\n(P0001)"
Run Code Online (Sandbox Code Playgroud)
这很容易解析,但这样做感觉是错误的。
解决这个问题的最佳方法是什么?是否可以有一个可以返回的自定义 AppResult 对象?
就像是:
{ success bool, error text, result <whatever type> }
Run Code Online (Sandbox Code Playgroud)
//编辑1 //
我想我更倾向于@Laurenz Albe 解决方案。
我的主要目标很简单:调用一个可以返回错误或一些数据的存储过程。
使用 RAISE 似乎可以完成此任务,并且 C++ 驱动程序允许轻松检查从查询返回的错误条件。
if ([error code returned from the query] == 90100)
{
// 1. Parse out my overly verbose error from the raw driver
// error string.
// 2. Handle the error.
}
Run Code Online (Sandbox Code Playgroud)
我还想知道如何使用自定义 SQLSTATE 代码而不是解析驱动程序字符串。
抛出“__404”可能意味着在我的 SP 执行过程中,它无法继续,因为找不到所需的某些记录。
当从我的应用程序调用 sql 函数时,我大致了解“__404”失败意味着什么以及如何处理它。这避免了解析驱动程序错误字符串的额外步骤。
我也看到了这可能是一个坏主意。
睡前阅读: https://www.postgresql.org/docs/current/static/errcodes-appendix.html
这有点基于意见,但我认为抛出错误是最好、最优雅的解决方案。这就是错误的目的!
为了区分各种错误消息,您可以使用以 6、8 或 9 开头的 SQLSTATE(这些未使用),然后您不必依赖于错误消息的措辞。
您可以通过以下方式引发此类错误
RAISE EXCEPTION SQLSTATE '90001' USING MESSAGE = 'my own error';
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10317 次 |
最近记录: |