1- use crate :: respond:: Respond ;
2- use crate :: { MockGuard , MockServer , Request , ResponseTemplate } ;
1+ use crate :: respond:: { Respond , RespondErr } ;
2+ use crate :: { ErrorResponse , MockGuard , MockServer , Request , ResponseTemplate } ;
33use std:: fmt:: { Debug , Formatter } ;
44use std:: ops:: {
55 Range , RangeBounds , RangeFrom , RangeFull , RangeInclusive , RangeTo , RangeToInclusive ,
@@ -270,7 +270,7 @@ impl Debug for Matcher {
270270#[ must_use = "`Mock`s have to be mounted or registered with a `MockServer` to become effective" ]
271271pub struct Mock {
272272 pub ( crate ) matchers : Vec < Matcher > ,
273- pub ( crate ) response : Box < dyn Respond > ,
273+ pub ( crate ) response : Result < Box < dyn Respond > , Box < dyn RespondErr > > ,
274274 /// Maximum number of times (inclusive) we should return a response from this Mock on
275275 /// matching requests.
276276 /// If `None`, there is no cap and we will respond to all incoming matching requests.
@@ -643,8 +643,14 @@ impl Mock {
643643
644644 /// Given a [`Request`] build an instance a [`ResponseTemplate`] using
645645 /// the responder associated with the `Mock`.
646- pub ( crate ) fn response_template ( & self , request : & Request ) -> ResponseTemplate {
647- self . response . respond ( request)
646+ pub ( crate ) fn response_template (
647+ & self ,
648+ request : & Request ,
649+ ) -> Result < ResponseTemplate , ErrorResponse > {
650+ match & self . response {
651+ Ok ( responder) => Ok ( responder. respond ( request) ) ,
652+ Err ( responder_err) => Err ( responder_err. respond_err ( request) ) ,
653+ }
648654 }
649655}
650656
@@ -670,7 +676,23 @@ impl MockBuilder {
670676 pub fn respond_with < R : Respond + ' static > ( self , responder : R ) -> Mock {
671677 Mock {
672678 matchers : self . matchers ,
673- response : Box :: new ( responder) ,
679+ response : Ok ( Box :: new ( responder) ) ,
680+ max_n_matches : None ,
681+ priority : 5 ,
682+ name : None ,
683+ expectation_range : Times ( TimesEnum :: Unbounded ( RangeFull ) ) ,
684+ }
685+ }
686+
687+ /// Instead of response with an HTTP reply, return a Rust error.
688+ ///
689+ /// This can simulate lower level errors, e.g., a [`ConnectionReset`] IO Error.
690+ ///
691+ /// [`ConnectionReset`]: std::io::ErrorKind::ConnectionReset
692+ pub fn respond_with_err < R : RespondErr + ' static > ( self , responder_err : R ) -> Mock {
693+ Mock {
694+ matchers : self . matchers ,
695+ response : Err ( Box :: new ( responder_err) ) ,
674696 max_n_matches : None ,
675697 priority : 5 ,
676698 name : None ,
0 commit comments