@@ -17,11 +17,11 @@ pub trait IntoTwirpResponse {
17
17
/// ```
18
18
/// use axum::body::Body;
19
19
/// use http::Response;
20
- /// use twirp::IntoTwirpResponse;
20
+ /// use twirp::{TwirpErrorResponse, IntoTwirpResponse} ;
21
21
/// # struct MyError { message: String }
22
22
///
23
23
/// impl IntoTwirpResponse for MyError {
24
- /// fn into_twirp_response(self) -> Response<Body > {
24
+ /// fn into_twirp_response(self) -> Response<TwirpErrorResponse > {
25
25
/// // Use TwirpErrorResponse to generate a valid starting point
26
26
/// let mut response = twirp::invalid_argument(&self.message)
27
27
/// .into_twirp_response();
@@ -35,7 +35,7 @@ pub trait IntoTwirpResponse {
35
35
///
36
36
/// The `Response` that `TwirpErrorResponse` generates can be used as a starting point,
37
37
/// adding headers and extensions to it.
38
- fn into_twirp_response ( self ) -> Response < Body > ;
38
+ fn into_twirp_response ( self ) -> Response < TwirpErrorResponse > ;
39
39
}
40
40
41
41
/// Alias for a generic error
@@ -182,26 +182,30 @@ impl TwirpErrorResponse {
182
182
pub fn insert_meta ( & mut self , key : String , value : String ) -> Option < String > {
183
183
self . meta . insert ( key, value)
184
184
}
185
- }
186
185
187
- impl IntoTwirpResponse for TwirpErrorResponse {
188
- fn into_twirp_response ( self ) -> Response < Body > {
189
- IntoResponse :: into_response ( self )
186
+ pub fn into_axum_body ( self ) -> Body {
187
+ let json =
188
+ serde_json:: to_string ( & self ) . expect ( "JSON serialization of an error should not fail" ) ;
189
+ Body :: new ( json)
190
190
}
191
191
}
192
192
193
- impl IntoResponse for TwirpErrorResponse {
194
- fn into_response ( self ) -> Response < Body > {
193
+ impl IntoTwirpResponse for TwirpErrorResponse {
194
+ fn into_twirp_response ( self ) -> Response < TwirpErrorResponse > {
195
195
let mut headers = HeaderMap :: new ( ) ;
196
196
headers. insert (
197
197
header:: CONTENT_TYPE ,
198
198
HeaderValue :: from_static ( "application/json" ) ,
199
199
) ;
200
200
201
- let json =
202
- serde_json:: to_string ( & self ) . expect ( "JSON serialization of an error should not fail" ) ;
201
+ let code = self . code . http_status_code ( ) ;
202
+ ( code, headers) . into_response ( ) . map ( |_| self )
203
+ }
204
+ }
203
205
204
- ( self . code . http_status_code ( ) , headers, json) . into_response ( )
206
+ impl IntoResponse for TwirpErrorResponse {
207
+ fn into_response ( self ) -> Response < Body > {
208
+ self . into_twirp_response ( ) . map ( |err| err. into_axum_body ( ) )
205
209
}
206
210
}
207
211
0 commit comments