11use alloc:: {
2+ borrow:: Cow ,
23 format,
34 string:: { String , ToString } ,
45} ;
@@ -8,20 +9,34 @@ use sqlite_nostd::{context, sqlite3, Connection, Context, ResultCode};
89use crate :: bson:: BsonError ;
910
1011#[ derive( Debug ) ]
11- pub struct SQLiteError ( pub ResultCode , pub Option < String > ) ;
12+ pub struct SQLiteError ( pub ResultCode , pub Option < Cow < ' static , str > > ) ;
13+
14+ impl SQLiteError {
15+ pub fn with_description ( code : ResultCode , message : impl Into < Cow < ' static , str > > ) -> Self {
16+ Self ( code, Some ( message. into ( ) ) )
17+ }
18+
19+ pub fn misuse ( message : impl Into < Cow < ' static , str > > ) -> Self {
20+ Self :: with_description ( ResultCode :: MISUSE , message)
21+ }
22+ }
1223
1324impl core:: fmt:: Display for SQLiteError {
1425 fn fmt ( & self , f : & mut core:: fmt:: Formatter < ' _ > ) -> core:: fmt:: Result {
15- write ! ( f, "{:?}" , self )
26+ write ! ( f, "SQLiteError: {:?}" , self . 0 ) ?;
27+ if let Some ( desc) = & self . 1 {
28+ write ! ( f, ", desc: {}" , desc) ?;
29+ }
30+ Ok ( ( ) )
1631 }
1732}
1833
1934impl SQLiteError {
2035 pub fn apply_to_ctx ( self , description : & str , ctx : * mut context ) {
2136 let SQLiteError ( code, message) = self ;
2237
23- if message . is_some ( ) {
24- ctx. result_error ( & format ! ( "{:} {:}" , description, message . unwrap ( ) ) ) ;
38+ if let Some ( msg ) = message {
39+ ctx. result_error ( & format ! ( "{:} {:}" , description, msg ) ) ;
2540 } else {
2641 let error = ctx. db_handle ( ) . errmsg ( ) . unwrap ( ) ;
2742 if error == "not an error" {
@@ -47,7 +62,7 @@ impl<T> PSResult<T> for Result<T, ResultCode> {
4762 if message == "not an error" {
4863 Err ( SQLiteError ( code, None ) )
4964 } else {
50- Err ( SQLiteError ( code, Some ( message) ) )
65+ Err ( SQLiteError ( code, Some ( message. into ( ) ) ) )
5166 }
5267 } else if let Ok ( r) = self {
5368 Ok ( r)
@@ -65,18 +80,18 @@ impl From<ResultCode> for SQLiteError {
6580
6681impl From < serde_json:: Error > for SQLiteError {
6782 fn from ( value : serde_json:: Error ) -> Self {
68- SQLiteError ( ResultCode :: ABORT , Some ( value. to_string ( ) ) )
83+ SQLiteError :: with_description ( ResultCode :: ABORT , value. to_string ( ) )
6984 }
7085}
7186
7287impl From < core:: fmt:: Error > for SQLiteError {
7388 fn from ( value : core:: fmt:: Error ) -> Self {
74- SQLiteError ( ResultCode :: INTERNAL , Some ( format ! ( "{}" , value) ) )
89+ SQLiteError :: with_description ( ResultCode :: INTERNAL , format ! ( "{}" , value) )
7590 }
7691}
7792
7893impl From < BsonError > for SQLiteError {
7994 fn from ( value : BsonError ) -> Self {
80- SQLiteError ( ResultCode :: ERROR , Some ( value. to_string ( ) ) )
95+ SQLiteError :: with_description ( ResultCode :: ERROR , value. to_string ( ) )
8196 }
8297}
0 commit comments