【问题标题】:How to handle server side errors in angularjs如何处理angularjs中的服务器端错误
【发布时间】:2014-09-24 23:03:15
【问题描述】:

如何使用 angularjs 处理服务器端错误。我看到了一些解决方案,例如How to properly handle server side errors?,但它们并不真正适合我的需求/也许我需要改变我的失败行为。请注意,我正在处理服务器端的路由。

我的问题是在服务器端我运行了一些 mongo 查询,这些查询返回到我的路线。请注意,这些查询也可能会生成自定义错误(例如字段的长度不合适)。例如:

服务器端

配料控制器

controller.getIngredient = function(cb) {
    Ingredient.findOne({},cb)
}

在我的路由处理程序中,我调用了这个函数:

function(req, res) {
ingredientController.getIngredient(function(err, data) {
    if (err)
        res.json({
            error: 1
        })
    else
        res.json({
            error: 0,
            data: 'success'
        })
})
}

请注意,json 中也可能包含错误消息。

客户端

productServices.getIngredient()
        .success(function(result) {
             //error should be handled here e.g. result.error === 1
             $scope.ingredient = result.data
        })
        .error(function(err) {
             console.log('error ' + err)
        })

我做得对吗?如果是,那我应该如何给用户一些反馈。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    一种解决方案是创建一个显示错误消息的服务和指令。在主模板中加载指令,然后使用服务对其进行更新。

    另一种选择是使用angular-growl 库:

    angular.module('MyModule').service(
      'MyService',
      function (growl) {
        this.getDatabaseResult = function () {
          getResult().then(
            function (result) {
              growl.addSuccessMessage('Success!');
            },
            function (error) {
              growl.addErrorMessage('Get Database Result Error: ' + error);
            }
          );
        }
      }
    );
    

    【讨论】:

    • 所以我需要在每个ajax 请求的success 中使用error 参数调用此服务的getDatabaseResult?你也可以更新你的结果,它不是一般的 - 你可以保留一般形式 - 但它适用于我的确切问题?
    • @Pio 你会调用咆哮的 addSuccessMessage 或 addErrorMessage
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2011-07-24
    • 1970-01-01
    • 2022-07-05
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多