javascript - 如何使用 TypeScript 处理异常消息?

标签 javascript typescript

我的代码如下所示:

class UserService implements IUserService {

    data: IUserServiceData = {
        expirationDate: null,
        isAuthenticated: false,
    };

    static $inject = [];

    constructor () {}

    isAuthenticated = () => {
        if (this.data.isAuthenticated && !this.isAuthenticationExpired(this.data.expirationDate)) {
            return true;
        } else {
            try {
                this.retrieveSavedData();
            } catch (e) {
                return false;
                // throw new NoAuthenticationException('Authentication not found');
            }
            return true;
        }
    };

    // Original Javascript code here
    //function AuthenticationRetrievalException(message) {
    //    this.name = 'AuthenticationRetrieval';
    //   this.message = message;
    //}

    AuthenticationRetrievalException = (message) => {
        this.name = 'AuthenticationRetrieval';
        this.message = message;
    }

    retrieveSavedData = () => {
        var savedData = this.utilityService.userCache.get('data');
        if (typeof savedData === 'undefined') {
            throw new AuthenticationRetrievalException('No authentication data exists');
        } else if (isAuthenticationExpired(savedData.expirationDate)) {
            throw new AuthenticationExpiredException('Authentication token has already expired');
        } else {
            this.data = savedData;
            this.setHttpAuthHeader();
        }
    }


} 

我应该如何处理这个。在我开始尝试转换之前我的 JavaScript 源代码中的引用?

我不知道如何在 Typescript 中编写这部分代码:

    AuthenticationRetrievalException = (message) => {
        this.name = 'AuthenticationRetrieval';
        this.message = message;
    }

最佳答案

如果我理解你的意思并且你想用自定义消息抛出一个错误,你可以像这样使用类 Error:

throw new Error("Authentication not found");

但我不确定这是不是你想要做的。

关于javascript - 如何使用 TypeScript 处理异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25012955/

相关文章:

typescript - 如何在 typescript 中取消回调 hell

angular - 只运行一次订阅

angular - 让用户 : User = new User (. ...) 为什么这对我不起作用?

javascript - 当在 div 中检测到垂直溢出时,有没有办法触发事件?

javascript - 如何在 jQuery 中进行 if-then 简写?这些可以链接吗?

javascript - 在我的表单输入旁边添加一个具有动态大小的标签

typescript - 为可以具有不同结构的对象参数定义类型

javascript - 尝试使用 requirejs 实例化 Marionette 应用程序时出现“对象不是函数”错误

java - 用于针对 Java servlet 进行身份验证的非 Java Web 应用程序

javascript - .prop 的 JQuery typescript 定义?