Skip to content

Commit 180d0a9

Browse files
authored
🐛 正确显示格式化错误 (#1310)
1 parent 811f148 commit 180d0a9

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

packages/message/server.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,19 @@ type ApiFunction = (params: any, con: IGetSender) => Promise<any> | any | void;
104104
type ApiFunctionSync = (params: any, con: IGetSender) => any;
105105
type 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+
107120
export 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

Comments
 (0)