pgwire/
error_or_notice.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::borrow::Cow;
16
17use risingwave_common::error::code::PostgresErrorCode;
18use risingwave_common::error::error_request_copy;
19use thiserror_ext::AsReport;
20
21/// ErrorOrNoticeMessage defines messages that can appear in ErrorResponse and NoticeResponse.
22pub struct ErrorOrNoticeMessage<'a> {
23    pub severity: Severity,
24    pub error_code: PostgresErrorCode,
25    pub message: Cow<'a, str>,
26}
27
28impl<'a> ErrorOrNoticeMessage<'a> {
29    /// Create a Postgres error message from an error, with the error code and message extracted from the error.
30    pub fn error(error: &(dyn std::error::Error + 'static)) -> Self {
31        let message = error.to_report_string_pretty();
32        let error_code = error_request_copy::<PostgresErrorCode>(error)
33            .filter(|e| e.is_error()) // should not be warning or success
34            .unwrap_or(PostgresErrorCode::InternalError);
35
36        Self {
37            severity: Severity::Error,
38            error_code,
39            message: Cow::Owned(message),
40        }
41    }
42
43    /// Create a Postgres notice message from a string.
44    pub fn notice(message: &'a str) -> Self {
45        Self {
46            severity: Severity::Notice,
47            error_code: PostgresErrorCode::SuccessfulCompletion,
48            message: Cow::Borrowed(message),
49        }
50    }
51}
52
53/// Severity: the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING,
54/// NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these.
55/// Always present.
56#[derive(PartialEq, Eq, Clone, Debug)]
57pub enum Severity {
58    Error,
59    Fatal,
60    Panic,
61    Notice,
62    Warning,
63    Debug,
64    Log,
65    Info,
66}
67
68impl Severity {
69    pub fn as_str(&self) -> &str {
70        match self {
71            Severity::Error => "ERROR",
72            Severity::Fatal => "FATAL",
73            Severity::Panic => "PANIC",
74            Severity::Notice => "NOTICE",
75            Severity::Warning => "WARNING",
76            Severity::Debug => "DEBUG",
77            Severity::Log => "LOG",
78            Severity::Info => "INFO",
79        }
80    }
81}