简体   繁体   English

JavaScript初始化和错误处理

[英]Javascript initialisation and error handling

I am writing an Angular app, coming from a PHP background. 我正在编写一个来自PHP背景的Angular应用程序。 What is the standard approach to initialisation and error handling. 初始化和错误处理的标准方法是什么? For example take my JWT Token factory. 例如,以我的JWT令牌工厂为例。

app.factory('Token', ['jwt_decode', function(jwt_decode) {

    var token = null, expiry = null, role = null;

    return {

        get: function() {
            return token;
        },

        set: function(value) {

            token = value;

            var data = jwt_decode(token);

            expiry = data.exp;
            role = data.role;

        },

        clear: function()
        {
            // performed on session expiry or logout.
            token = null;
            expiry = null;
            role = null;
        },

        has: function()
        {
            return token !== null;
        },

        getRole: function()
        {
            return role;
        },

        getExpiry: function()
        {
            return expiry;
        }
    };

}]);

I have initialised my private variables as null but I have read some blogs which instead suggest I leave them as undefined. 我已经将我的私有变量初始化为null,但是我读了一些博客,建议我将它们保留为未定义状态。 If I leave them as undefined should my clean method set these back to undefined or null? 如果我将它们保留为undefined,我的clean方法是否应将其设置回undefined或null? If I set them to undefined I believe my has function should then be token !== undefined? 如果我将它们设置为undefined,我相信我的has函数应该是token!== undefined?

Lastly if say a invalid token was passed eg 123 how should this be handled, is it common to throw like I would in PHP? 最后,如果说传递了无效的令牌,例如123,应该如何处理,是否像在PHP中一样抛出异常? I am yet too see much error handling in JavaScript to know the best way to handle it? 我还看到JavaScript中有很多错误处理方法,无法知道处理错误的最佳方法?

Null or undefined is a matter of style. 空或未定义是样式问题。 Choose one of those and be consistent. 选择其中一项并保持一致。 The key in js test for falsy or thruthy values. js中的键测试伪造或虚假值。 That is your has method could return !!token, so if the token is null or undefined or '' will be false and true otherwise. 那就是你的has方法可能返回!! token,所以如果令牌为null或undefined,否则''为false和true。 It is a good practice to wrap your code in an self invoking anonymous function and make undefined as a parameter because is not a reserve word in js and anyone could assign a value to undefined. 最好将代码包装在自调用匿名函数中,然后将undefined设置为参数,因为这不是js中的保留字,任何人都可以为undefined赋值。

(function(angular, $, undefined){

}(angular,jQuery));

Exception handling you have try/catch to handle unexpected behavior or you can throw errors (throw 'Unexpected token'). 您可以使用try / catch异常处理来处理意外行为,也可以引发错误(引发“意外令牌”)。 Again you can catch the errors that you throw with try/catch 同样,您可以捕获使用try / catch引发的错误

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM