管理nodejs中的错误和转换

vulvrdjw  于 2023-03-01  发布在  Node.js
关注(0)|答案(1)|浏览(97)

我的nodejs应用程序使用基本的REST通信风格来允许HTML Web UI传递命令。
例如:

http://address/api/config/cmd1
http://address/api/config/cmd2
http://address/api/network/cmd3
...

作为回报,我的web用户界面得到一个JSON结果,格式如下:

{
  "success": true
}

{
  "success": false,
  "errorMsg": "Wrong parameter blabla"
}

我的问题是,我现在需要在客户端翻译错误消息(多种语言),而英语"errorMsg"太多变,太长,不能作为翻译键。
所以我需要一个"errorCode"(可能是一个整数),我正在nodejs应用程序中寻找一个策略来管理错误代码。我不知道通常是怎么做的,因为我通常使用throw new Error("message")将消息直接返回到web用户界面。
我不知道是为所有REST API创建一个uniq错误代码列表,还是为该API的每个子集创建一个上下文错误列表。

    • UPDATE**:最后,我选择了一个字符串错误id。例如,"此命令的错误参数"变为"WrongArgument",并将用于识别GUI端的错误,从而执行本地化过程。最后,我不需要使错误id唯一。
dgiusagp

dgiusagp1#

Using a custom Error class in the back-end with error identifier will allow the front-end to directly use its translation module, without modifications.
From your Server, one can process the standard error by creating a custom class, throw the class, catch it in your controller and send to the front-end the response with correct http status and error id.
The reasons are:
1 - Front-end code maintanability.
2 - Keeping errors systems data on back-end logs because they might be sensitive. It should not be return to the client side.
I agree with naming identifier code instead of using a code number. This because it s hard to pre-define a range for each error type (SQL, API, Authentication...). And it s harder when the error may be found in different service.
Scope: In the front-end service, i define a scope when calling the server, so that if there is need for a global error to be more specific, it is there. The scope is just a string with the name of the page where the ressources is used, also found in JSON lang files.
If you'd like, check this code out and feel free to give feedbacks, it will always help:
'https://codepen.io/Aymer-El/pen/OJoRVgZ'
Also leaving place for a debug message in the response may help front-end devs. Tho, this is optional.

相关问题