pgwire/error_or_notice.rs
1// Copyright 2022 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), pretty: bool) -> Self {
31 let message = if pretty {
32 error.to_report_string_pretty()
33 } else {
34 error.to_report_string()
35 };
36 let error_code = error_request_copy::<PostgresErrorCode>(error)
37 .filter(|e| e.is_error()) // should not be warning or success
38 .unwrap_or(PostgresErrorCode::InternalError);
39
40 Self {
41 severity: Severity::Error,
42 error_code,
43 message: Cow::Owned(message),
44 }
45 }
46
47 /// Create a Postgres notice message from a string.
48 pub fn notice(message: &'a str) -> Self {
49 Self {
50 severity: Severity::Notice,
51 error_code: PostgresErrorCode::SuccessfulCompletion,
52 message: Cow::Borrowed(message),
53 }
54 }
55}
56
57/// Severity: the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING,
58/// NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these.
59/// Always present.
60#[derive(PartialEq, Eq, Clone, Debug)]
61pub enum Severity {
62 Error,
63 Fatal,
64 Panic,
65 Notice,
66 Warning,
67 Debug,
68 Log,
69 Info,
70}
71
72impl Severity {
73 pub fn as_str(&self) -> &str {
74 match self {
75 Severity::Error => "ERROR",
76 Severity::Fatal => "FATAL",
77 Severity::Panic => "PANIC",
78 Severity::Notice => "NOTICE",
79 Severity::Warning => "WARNING",
80 Severity::Debug => "DEBUG",
81 Severity::Log => "LOG",
82 Severity::Info => "INFO",
83 }
84 }
85}