Marcus.Aurelianus
Marcus.Aurelianus

Reputation: 1518

Code cannot parse when return value directly in try catch block in a specific browser

I have a project that I need to test the compatibility of on a lot of browsers. Almost all of the browsers work fine, but I encounter code executing issues with a specific browser with user agent:

Mozilla/5.0 (Linux; Android 8.1.0;
OPP R11 Plus Build/OPM1.171019.011;
wV) AppleWebKit/537.36 (KHTML, like
Gecko) Version/4.0
Chrome/62.0.3202.84 Mobile
Safari/537.36 Mb2345Browser/15.6.2

When I try to run the following code inside an async function, the code never executes:

try {
    const jsonResult = await result.json();
    return jsonResult
} catch {
    return 'invalid json output';
}

However, if I change the code to

let jsonResult = 'invalid json output';
try {
    jsonResult = await result.json();
} catch (e) {
    console.log(e);
}
return jsonResult;

then the code works fine. Does anyone know why ==, I cannot debug because the browser disables the debug mode with Chrome.

Upvotes: 2

Views: 146

Answers (1)

DSDmark
DSDmark

Reputation: 1261

Because, this is the correct way to write this code.

async function getResult() {
  try {
    const jsonResult = await result.json();
    return jsonResult;
  } catch (error) {
    console.error(error);
    return 'invalid json output';
  }
}

Upvotes: 1

Related Questions