@@ -7,19 +7,27 @@ use std::error;
77use std:: fmt;
88use types:: { NpyDataType , TypeNum } ;
99
10- pub trait IntoPyErr {
11- fn into_pyerr ( self , msg : & str ) -> PyErr ;
10+ pub trait IntoPyErr : Into < PyErr > {
11+ fn into_pyerr ( self ) -> PyErr ;
12+ fn into_pyerr_with < D : fmt:: Display > ( self , impl FnOnce ( ) -> D ) -> PyErr ;
1213}
1314
1415pub trait IntoPyResult {
1516 type ValueType ;
16- fn into_pyresult ( self , msg : & str ) -> PyResult < Self :: ValueType > ;
17+ fn into_pyresult ( self ) -> PyResult < Self :: ValueType > ;
18+ fn into_pyresult_with < D : fmt:: Display > ( self , impl FnOnce ( ) -> D ) -> PyResult < Self :: ValueType > ;
1719}
1820
1921impl < T , E : IntoPyErr > IntoPyResult for Result < T , E > {
2022 type ValueType = T ;
21- fn into_pyresult ( self , msg : & str ) -> PyResult < T > {
22- self . map_err ( |e| e. into_pyerr ( msg) )
23+ fn into_pyresult ( self ) -> PyResult < Self :: ValueType > {
24+ self . map_err ( |e| e. into ( ) )
25+ }
26+ fn into_pyresult_with < D : fmt:: Display > (
27+ self ,
28+ msg : impl FnOnce ( ) -> D ,
29+ ) -> PyResult < Self :: ValueType > {
30+ self . map_err ( |e| e. into_pyerr_with ( msg) )
2331 }
2432}
2533
@@ -117,11 +125,24 @@ impl fmt::Display for ErrorKind {
117125
118126impl error:: Error for ErrorKind { }
119127
128+ impl From < ErrorKind > for PyErr {
129+ fn from ( err : ErrorKind ) -> PyErr {
130+ match err {
131+ ErrorKind :: PyToRust { .. } | ErrorKind :: FromVec { .. } | ErrorKind :: PyToPy ( _) => {
132+ PyErr :: new :: < exc:: TypeError , _ > ( format ! ( "{}" , err) )
133+ }
134+ }
135+ }
136+ }
137+
120138impl IntoPyErr for ErrorKind {
121- fn into_pyerr ( self , msg : & str ) -> PyErr {
139+ fn into_pyerr ( self ) -> PyErr {
140+ Into :: into ( self )
141+ }
142+ fn into_pyerr_with < D : fmt:: Display > ( self , msg : impl FnOnce ( ) -> D ) -> PyErr {
122143 match self {
123144 ErrorKind :: PyToRust { .. } | ErrorKind :: FromVec { .. } | ErrorKind :: PyToPy ( _) => {
124- PyErr :: new :: < exc:: TypeError , _ > ( format ! ( "{}, msg: {}" , self , msg) )
145+ PyErr :: new :: < exc:: TypeError , _ > ( format ! ( "{} msg: {}" , self , msg( ) ) )
125146 }
126147 }
127148 }
0 commit comments