简体   繁体   English

如何在一个地方处理所有错误?

[英]How should I handle all my errors in one place?

I would like to know how I should handle my errors in one place using node.js 我想知道如何使用node.js在一个地方处理错误

This is how I did: 这是我做的:

First I create loggers/errors.js 首先,我创建loggers / errors.js

And inside I have this object: 在里面,我有这个对象:

var Errors = {
 bad_request: 'Some error related with bad request'
};

Than, in other files I just require this file, and when some statement or some error can occur, i just call: 然后,在其他文件中,我只需要此文件,并且当某些语句或某些错误可能发生时,我只需调用:

var Errors = require('../loggers/errors');

if (something here) {
 console.log(Errors.bad_request);
}

I would like to know if this is a good approach, if I am doing right, or if there is a module that already does what I want, but with extra features. 我想知道这是否是一个好方法,是否做得对,或者是否有一个模块已经可以满足我的要求,但是具有额外的功能。

You could do something like this: 您可以执行以下操作:

module.exports = {
    BadRequest: 'Request was bad',
    Timeout: 'Server timed out'
}

And require it in the main file 并在主文件中要求它

var Error = require ('../loggers/errors.js');

if(statement) {
    console.log (Error.BadRequest );
}

You need to declare module.exports or it won't be able to be required. 您需要声明module.exports,否则将不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该如何处理Firebase登录错误? - How should I handle firebase login errors? 如何在一处处理所有Kendo UI对象的401? - How to handle 401 for all Kendo UI objects in one place? 我应该如何将脚本放置在html文件中? - How should I place my scripts in my html files? 如何将我的消息错误保存在日志文件中? 它在应该写入错误一时写入成功消息 - How can I save my message errors in a log file? it writes the success message when it should write the error one 我应该将所有JavaScript源复制到一个文件中吗? - Should I copy all my JavaScript sources into one single file? 我应该将所有 js 文件包含到一个 js 文件中吗? - Should i include all my js files to one js file? 如何在一个地方检测图像上的403错误? - How to detect 403 Errors on images in one place? 如果我的 Redux 商店中的 state 是可观察的,我应该在每个需要它的组件中订阅它还是在一个地方订阅并作为输入传递? - If a state in my Redux Store is an observable, should I subscribe to it in each component that needs it or subscribe in one place and pass as inputs? Jquery 方式在一处处理所有 ajax 成功事件 - Jquery way to handle all ajax success events in one place 如何快速处理并捕获我的错误 - How to have express handle and capture my errors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM