代码之家  ›  专栏  ›  技术社区  ›  Lorraine Ram-El

如果在“try-catch”块中发生错误,并且最终仍在中运行代码,如何返回?

  •  0
  • Lorraine Ram-El  · 技术社区  · 4 年前

    try 块,并仍在中运行清理代码 finally

    我用的是 shouldContinue 那就定了 true 最初,并将其设置为 false 如果执行不应继续,则在catch块内部。

    async uploadToServer() {
        let response;
        let shouldContinue = true;
    
        try {
            response = await this.uploderService.uploadFileToServer();
    
        } catch (error) {
            this.displayUploadError(error);
            shouldContinue = false;
    
        } finally {
            // run cleanup code anyway
            this.resetSession();
        }
    
        if (!shouldContinue) {
            return;
        }
    
        this.saveResponse(response);
        // continue execution here
        // ...
    
    }
    

    在函数内部发生错误后,是否有更好的方法退出函数 尝试 最后 ?

    3 回复  |  直到 4 年前
        1
  •  2
  •   Adam Jenkins    4 年前

    一种方法(可能是我个人更喜欢的方法)是简单地将所有内容放在try中(如果可能-例如,如果try中没有任何其他内容会抛出不相关的错误):

    async uploadToServer() {
    
        try {
            const response = await this.uploderService.uploadFileToServer();
            this.saveResponse(response);
            // continue execution here
            // ...
        } catch (error) {
            this.displayUploadError(error);
        } finally {
            // run cleanup code anyway
            this.resetSession();
        }
    
    }
    

    另一种方法是返回捕获(最终仍然运行):

    async uploadToServer() {
        let response;
    
        try {
            response = await this.uploderService.uploadFileToServer();
        } catch (error) {
            this.displayUploadError(error);
            return;
        } finally {
            // run cleanup code anyway
            this.resetSession();
        }
    
        this.saveResponse(response);
        // continue execution here
        // ...
    
    }
    
    
        2
  •  1
  •   Moamen Ragab    4 年前

    不管怎样,最终都将执行try或catch。

    推荐文章