littlegraph_query_api/
error.rs1use axum::http::StatusCode;
2use axum::response::{IntoResponse, Response};
3use serde::Serialize;
4
5pub type Result<T> = std::result::Result<T, QueryApiError>;
6
7#[derive(Debug, thiserror::Error)]
8pub enum QueryApiError {
9 #[error("invalid Query API server configuration: {0}")]
10 InvalidConfiguration(String),
11 #[error("Query API database error: {0}")]
12 Database(String),
13 #[error("Query API HTTP error: {0}")]
14 Http(String),
15 #[error(transparent)]
16 Io(#[from] std::io::Error),
17}
18
19#[derive(Clone, Debug)]
20pub(crate) struct HttpError {
21 pub(crate) status: StatusCode,
22 pub(crate) code: &'static str,
23 pub(crate) message: String,
24 pub(crate) authenticate: bool,
25}
26
27#[derive(Serialize)]
28struct ErrorEnvelope<'a> {
29 errors: [ErrorBody<'a>; 1],
30}
31
32#[derive(Serialize)]
33struct ErrorBody<'a> {
34 code: &'a str,
35 message: &'a str,
36}
37
38impl HttpError {
39 pub(crate) fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
40 Self {
41 status,
42 code,
43 message: message.into(),
44 authenticate: false,
45 }
46 }
47
48 pub(crate) fn invalid(message: impl Into<String>) -> Self {
49 Self::new(
50 StatusCode::BAD_REQUEST,
51 "Neo.ClientError.Request.Invalid",
52 message,
53 )
54 }
55
56 pub(crate) fn unauthorized(message: impl Into<String>) -> Self {
57 let mut error = Self::new(
58 StatusCode::UNAUTHORIZED,
59 "Neo.ClientError.Security.Unauthorized",
60 message,
61 );
62 error.authenticate = true;
63 error
64 }
65
66 pub(crate) fn not_found(tx_id: &str) -> Self {
67 Self::new(
68 StatusCode::NOT_FOUND,
69 "Neo.ClientError.Request.Invalid",
70 format!(
71 "Transaction with Id: \"{tx_id}\" was not found. It may have timed out and \
72 therefore rolled back or the routing header 'neo4j-cluster-affinity' was not \
73 provided."
74 ),
75 )
76 }
77
78 pub(crate) fn into_formatted_response(
79 self,
80 content_type: &'static str,
81 json_lines: bool,
82 ) -> Response {
83 let envelope = ErrorEnvelope {
84 errors: [ErrorBody {
85 code: self.code,
86 message: &self.message,
87 }],
88 };
89 let mut body = if json_lines {
90 serde_json::to_vec(&serde_json::json!({
91 "$event": "Error",
92 "_body": envelope,
93 }))
94 } else {
95 serde_json::to_vec(&envelope)
96 }
97 .expect("serializing a Query API error envelope cannot fail");
98 if json_lines {
99 body.push(b'\n');
100 }
101 let mut response = (
102 self.status,
103 [(axum::http::header::CONTENT_TYPE, content_type)],
104 body,
105 )
106 .into_response();
107 if self.authenticate {
108 response.headers_mut().insert(
109 axum::http::header::WWW_AUTHENTICATE,
110 axum::http::HeaderValue::from_static(
111 "Basic realm=\"Neo4j\", Bearer realm=\"Neo4j\"",
112 ),
113 );
114 }
115 response
116 }
117}
118
119impl IntoResponse for HttpError {
120 fn into_response(self) -> Response {
121 self.into_formatted_response("application/json", false)
122 }
123}