从异常中提取用户定义的错误消息

时间:2013-10-21 11:25:42

标签: sql postgresql

在我的存储过程中,我只检查了一个特定的条件,如果该条件失败,我将抛出异常。如下,

Raise Exception '%', 'Hello world';

它工作正常,但错误消息Hello world还附带了一些其他错误代码,如下面的东西,如我的前端,

DA00014:ERROR: P0001: Hello world
|___________________|
        |
      I really dont want this part to get displayed in the front end.

是否有任何正确的方法可以过滤/从抛出的异常中提取正确的消息。

[注意: 请不要建议我做一些字符串操作。]

DBMS      : POSTGRESQL 9.0.3
Driver    : Npgsql 1.0
Front End : VB.net

4 个答案:

答案 0 :(得分:1)

Npgsql Fastpath

如果NpgsqlException.Errors在您的异常处理程序中为空,那么您很可能遇到Npgsql Fastpath中的错误(我认为它仍然是一个错误)。版本2中Here is the offending line但版本1中存在相同的问题。

它基本上归结为这个代码,其中构造了一个正确的NpgsqlError,然后在通过调用ToString()来引发异常时抛弃它。

NpgsqlError e = new NpgsqlError(conn.BackendProtocolVersion, stream);
throw new NpgsqlException(e.ToString());

修复程序就像将代码更改为此并使用NpgsqlException已支持的功能在构造函数中接收NpgsqlError列表一样简单。

NpgsqlError e = new NpgsqlError(conn.BackendProtocolVersion, stream);
throw new NpgsqlException(new ArrayList(e));

总而言之,如果没有字符串操作,除非编译自己的Npgsql版本修补问题,否则不能这样做。

Npgsql的

如果您没有使用Fastpath,则抛出的NpgsqlException对象包含Errors属性,该属性应为非空列表。这是从第一个错误中提取消息的示例。

(ex.Errors[0] as NpgsqlError).Message

答案 1 :(得分:0)

试试这个..
 在商店流程中,在邮件中添加一个额外的字符。 e.g

Raise Exception '%', '|Hello world';

在前端split your message on character "|",并显示数组的第二个索引。 e.g

    Try
      ' your code..
    Catch ex As Exception
        Dim arr As String() = ex.Message.Split("|")
        If arr.Count > 1 Then
            MessageBox.Show(Convert.ToString(arr(1)))
        Else
            MessageBox.Show(Convert.ToString(ex.Message))
        End If
    End Try

答案 2 :(得分:0)

如果我理解,你可以尝试一次

IF condition match -- (your condition)
BEGIN
    RAISERROR('Hello world', 16,16)
    return
 END

和异常

可以像

一样使用
catch(exception ex)
{
  // ex.Message
  //  ex.InnerException.Message
}

答案 3 :(得分:0)

这应该有效:

Catch ex As Exception

    lblMsg.Text = ex.Message.Replace("ERROR: P0001: ", "")

End Try
相关问题