Request failed with status 404: invalid session id

I am running some scenarios in a WebriverIo framework and if some scenario fails I get this exception
404: invalid session id.
I have tried multiple things below is the code. If you can suggest what should be my approach so that the issue doesn’t happen in console

exports.config = {
// Other configuration settings

beforeScenario: function (world) {
    if (browser && browser.sessionId) {
        browser.reloadSession();
    } else {
        browser.url('');
    }
    console.log('Starting scenario: ', world.name);
},

afterStep: function (step, scenario, { error, duration, passed }) {
    if (!passed) {
        console.error(`Step failed: ${step.text} in scenario ${scenario.name}`);
        browser.saveScreenshot(`./screenshots/${scenario.name}_step_${step.index}.png`);
    }
},

afterScenario: function (world, result) {
    if (result.status === 'failed') {
        console.log(`Scenario failed: ${world.name}`);
        browser.saveScreenshot(`./screenshots/${world.name}_failed.png`);
        if (browser && browser.sessionId) {
            try {
                browser.deleteSession();
            } catch (err) {
                console.warn('Failed to delete session:', err.message);
            }
        }
    }
    if (browser && browser.sessionId) {
        browser.reloadSession();
    }
},

// Other hooks and configuration settings

};