在Postgres中,我们使用以下代码获取异常的“堆栈跟踪”:
EXCEPTION WHEN others THEN
GET STACKED DIAGNOSTICS v_error_stack = PG_EXCEPTION_CONTEXT;
对于“自然”异常,这很好用,但是如果我们使用
RAISE EXCEPTION 'This is an error!';
...那么就没有堆栈跟踪。根据邮件列表条目,这可能是故意的,尽管我一生都无法弄清原因。这让我想找出引发异常的另一种方法,而不是使用RAISE
。我只是想念一些明显的东西吗?有人对此有把戏吗?是否有我可以让Postgres抛出的异常,其中包含我选择的字符串,这样我不仅可以在错误消息中得到我的字符串,而且还可以得到完整的堆栈跟踪信息?
这是一个完整的示例:
CREATE OR REPLACE FUNCTION error_test() RETURNS json AS $$
DECLARE
v_error_stack text;
BEGIN
-- Comment this out to see how a "normal" exception will give you the stack trace
RAISE EXCEPTION 'This exception will not get a stack trace';
-- This will give a divide by zero error, complete with stack trace
SELECT 1/0;
-- In case of any exception, wrap it in error object and send it back as json
EXCEPTION WHEN others THEN
-- If the exception we're catching is one that Postgres threw,
-- like a divide by zero error, then this will get the full
-- stack trace of the place where the exception was thrown.
-- However, since we are catching an exception we raised manually
-- using RAISE EXCEPTION, there is no context/stack trace!
GET STACKED DIAGNOSTICS v_error_stack = PG_EXCEPTION_CONTEXT;
RAISE WARNING 'The stack trace of the error is: "%"', v_error_stack;
return to_json(v_error_stack);
END;
$$ LANGUAGE plpgsql;
error_info
啊 看起来像自定义类型。