如何在Golang中检查通过RAISE EXCEPTION引发的自定义Postgres异常?

huangapple go评论102阅读模式
英文:

How to check for custom Postgres exceptions raised via RAISE EXCEPTION in Golang?

问题

我正在使用Postgres和Golang,通过pgx进行操作。

我有一个触发器函数,类似以下代码:

CREATE OR REPLACE FUNCTION foo() 
RETURNS TRIGGER AS
$$
BEGIN
    IF (bar = 'baz') THEN
        -- something
    ELSE
        RAISE EXCEPTION 'oops error';
    END IF;
    RETURN NEW;
END;
$$
LANGUAGE plpgsql;

在Go代码中,如何检查oops error呢?

目前我这样做:

errOops := errors.New("ERROR: oops error (SQLSTATE P0001)")
err := myDBFunc()
if errors.Is(err, errOops) {

}

但我想知道是否有更好的方法,而不是依赖硬编码的消息。

英文:

I'm using Postgres with Golang via pgx

I've a trigger function something like the following:

CREATE OR REPLACE FUNCTION foo() 
RETURNS TRIGGER AS
$$
BEGIN
    IF (bar = 'baz') THEN
        -- something
    ELSE
        RAISE EXCEPTION 'oops error';
    END IF;
    RETURN NEW;
END;
$$
LANGUAGE plpgsql;

How do I check for oops error in Go code?

The way I'm doing it now is:

errOops := errors.New("ERROR: oops error (SQLSTATE P0001)")
err := myDBFunc()
if errors.Is(err, errOops) {

}

But I wonder if there's a better way other than relying on the hardcoded message.

答案1

得分: 3

应该阅读维基百科:pgx中的错误处理

所以我可以这样做:

var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "P0001" {

}

或者类似的方式。

英文:

Should have read the Wiki: Error Handling in pgx

So I can do:

var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "P0001" {

}

or something similar.

答案2

得分: 1

你可以在文档的附录A中找到这些信息:它将是一个raise_exception,而SQLSTATE是P0001

英文:

You can find that information in appendix A of the documentation: it will be a raise_exception, and the SQLSTATE is P0001.

huangapple
  • 本文由 发表于 2022年10月18日 18:40:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/74109610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定