在 Postgres 中,我们使用以下代码获取异常的“堆栈跟踪”:
EXCEPTION WHEN others THEN
GET STACKED DIAGNOSTICS v_error_stack = PG_EXCEPTION_CONTEXT;
Run Code Online (Sandbox Code Playgroud)
这适用于“自然”异常,但如果我们使用
RAISE EXCEPTION 'This is an error!';
Run Code Online (Sandbox Code Playgroud)
...然后没有堆栈跟踪。根据邮件列表条目,这可能是故意的,尽管我终生无法弄清楚原因。这让我想找出另一种抛出异常的方法,而不是使用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 …Run Code Online (Sandbox Code Playgroud) 这很好地说明了这个问题:
当 b 列是文本类型而不是数组时,以下工作:
select *
from json_to_record('{"a":1,"b":["hello", "There"],"c":"bar"}')
as x(a int, b text, d text);
a | b | d
---+--------------------+---
1 | ["hello", "There"] |
Run Code Online (Sandbox Code Playgroud)
但是,如果我将该b列定义为数组,则会出现此错误:
select *
from json_to_record('{"a":1,"b":["hello", "There"],"c":"bar"}')
as x(a int, b text[], d text)
ERROR: malformed array literal: "["hello", "There"]"
DETAIL: "[" must introduce explicitly-specified array dimensions.
Run Code Online (Sandbox Code Playgroud)
如何说服/强制json_to_record(或json_populate_record)将 JSON 数组转换为目标列类型的 Postgres 数组?