Skip to content

Commit 1a10f2a

Browse files
authored
feat: add more response helpers (#2315)
1 parent 6ffedf0 commit 1a10f2a

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

Diff for: crates/json-rpc/src/packet.rs

+15
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,21 @@ impl<Payload, ErrData> ResponsePacket<Payload, ErrData> {
297297
}
298298
}
299299

300+
/// Returns the first error code in this packet if it contains any error responses.
301+
pub fn first_error_code(&self) -> Option<i64> {
302+
self.as_error().map(|error| error.code)
303+
}
304+
305+
/// Returns the first error message in this packet if it contains any error responses.
306+
pub fn first_error_message(&self) -> Option<&str> {
307+
self.as_error().map(|error| error.message.as_ref())
308+
}
309+
310+
/// Returns the first error data in this packet if it contains any error responses.
311+
pub fn first_error_data(&self) -> Option<&ErrData> {
312+
self.as_error().and_then(|error| error.data.as_ref())
313+
}
314+
300315
/// Returns a all [`Response`].
301316
pub fn responses(&self) -> &[Response<Payload, ErrData>] {
302317
match self {

Diff for: crates/json-rpc/src/response/mod.rs

+10
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ impl<Payload, ErrData> Response<Payload, ErrData> {
8282
}
8383
}
8484

85+
/// Returns the payload of this response
86+
pub const fn payload(&self) -> &ResponsePayload<Payload, ErrData> {
87+
&self.payload
88+
}
89+
8590
/// Create a new error response for an internal error with additional data.
8691
pub const fn internal_error_with_obj(id: Id, data: ErrData) -> Self
8792
where
@@ -117,6 +122,11 @@ impl<Payload, ErrData> Response<Payload, ErrData> {
117122
pub const fn is_error(&self) -> bool {
118123
self.payload.is_error()
119124
}
125+
126+
/// Returns the error code if the payload of this response is an [`ErrorPayload`].
127+
pub fn error_code(&self) -> Option<i64> {
128+
self.payload().error_code()
129+
}
120130
}
121131

122132
impl<Payload, ErrData> Response<Payload, ErrData>

Diff for: crates/json-rpc/src/response/payload.rs

+10
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,16 @@ impl<Payload, ErrData> ResponsePayload<Payload, ErrData> {
111111
}
112112
}
113113

114+
/// Returns the error code if this a [`ResponsePayload::Failure`]
115+
pub fn error_code(&self) -> Option<i64> {
116+
self.as_error().map(|err| err.code)
117+
}
118+
119+
/// Returns the error data if this a [`ResponsePayload::Failure`]
120+
pub fn error_data(&self) -> Option<&ErrData> {
121+
self.as_error().and_then(|err| err.data.as_ref())
122+
}
123+
114124
/// Returns `true` if the response payload is a success.
115125
pub const fn is_success(&self) -> bool {
116126
matches!(self, Self::Success(_))

0 commit comments

Comments
 (0)