发布于 2026-01-06 0 阅读
0

Node.js Express 应用程序错误处理 DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

Node.js Express 应用程序中的错误处理

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

各位开发者朋友们好。我想和大家分享一些关于Express应用程序中错误处理的想法。

目标:让人们分享各种想法可以帮助所有阅读/讨论的人建立自己的错误处理机制或加强现有的错误处理机制。

要求:应能处理一个或多个服务中抛出的错误,包括自身服务以及第三方库使用服务中的错误。

我的想法:

1. Creation of StatusError such as
https://thepracticaldev.s3.amazonaws.com/i/u6rxsufyjqvplr3364da.png

2. Throwing this error in services that are part of our business domain with         
    meaningful statuses, such as 400, 404, 401 etc.

3. Throwing this error in services that handle consuming 3rd party API with 
    such status that has semantic meaning, even if it may be slightly different 
    from the one in API. One could also add additional info comprised of data 
    successfully computed before such error. 

    e.g. Throwing 404 while trying to find 3rd party resource connected to some 
         in our base even though third party API may throw different error but 
         with such response that corresponds 404. One could also add name of 
         resource from our base in message to help further solving the issue.

4. These errors could be caught in route handlers and sent further down the 
   pipe to error handler.

5. Error handler could call the appropriate error handling module which can do 
    multiple, separated actions, such as logging, special handling for some of 
    the errors, etc.

我非常期待听到你的想法。

文章来源:https://dev.to/strahinjalak/error-handling-in-node-js-express-applications-5d08