Home > Enterprise >  How to return if an error occurs inside a `try-catch` block, and still run code in finally?
How to return if an error occurs inside a `try-catch` block, and still run code in finally?

Time:01-01

I'm trying to exit the function if an error occurs inside the try block, and still run cleanup code in finally.

I'm doing it by using shouldContinue that is set to true initially, and set it to false inside the catch block if the execution shouldn't continue.

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
    // ...

}

Is there a better way to exit the function after an error occurs inside the try block and still run code in finally?

CodePudding user response:

One way (probably my personal preferred way) is to simply put everything inside the try (if possible - e.g. if nothing else inside the try could throw an unrelated error):

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();
    }

}

Another way is to return in the catch (finally still runs):

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
    // ...

}

CodePudding user response:

Finally will be executed anyway, either the try executed or catch.

  • Related