@@ -104,6 +104,19 @@ type ApiFunction = (params: any, con: IGetSender) => Promise<any> | any | void;
104104type ApiFunctionSync = ( params : any , con : IGetSender ) => any ;
105105type MiddlewareFunction = ( params : any , con : IGetSender , next : ( ) => Promise < any > | any ) => Promise < any > | any ;
106106
107+ const formatErrorToClient = ( e : any ) => {
108+ if ( ! e ) return `${ e } ` ;
109+ if ( typeof e ?. message === "string" ) return e . message ;
110+ if ( typeof e === "object" ) {
111+ try {
112+ return JSON . stringify ( e ) ;
113+ } catch {
114+ // ignored
115+ }
116+ }
117+ return e . toString ( ) ;
118+ } ;
119+
107120export class Server {
108121 private apiFunctionMap : Map < string , ApiFunction > = new Map ( ) ;
109122
@@ -159,7 +172,7 @@ export class Server {
159172 data && con . sendMessage ( { code : 0 , data } ) ;
160173 } )
161174 . catch ( ( e : Error ) => {
162- con . sendMessage ( { code : - 1 , message : e . message || e . toString ( ) } ) ;
175+ con . sendMessage ( { code : - 1 , message : formatErrorToClient ( e ) } ) ;
163176 this . logger . error ( "connectHandle error" , Logger . E ( e ) ) ;
164177 } ) ;
165178 return true ;
@@ -191,15 +204,15 @@ export class Server {
191204 }
192205 } )
193206 . catch ( ( e : Error ) => {
194- sendResponse ( { code : - 1 , message : e . message || e . toString ( ) } ) ;
207+ sendResponse ( { code : - 1 , message : formatErrorToClient ( e ) } ) ;
195208 this . logger . error ( "messageHandle error" , Logger . E ( e ) ) ;
196209 } ) ;
197210 return true ;
198211 } else {
199212 sendResponse ( { code : 0 , data : ret } ) ;
200213 }
201214 } catch ( e : any ) {
202- sendResponse ( { code : - 1 , message : e . message || e . toString ( ) } ) ;
215+ sendResponse ( { code : - 1 , message : formatErrorToClient ( e ) } ) ;
203216 this . logger . error ( "messageHandle error" , Logger . E ( e ) ) ;
204217 }
205218 } else {
0 commit comments