Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try catch example #36

Open
jorge-melnik opened this issue Aug 26, 2024 · 0 comments
Open

Try catch example #36

jorge-melnik opened this issue Aug 26, 2024 · 0 comments

Comments

@jorge-melnik
Copy link

// Nests 1 level for each error handling block
async function readData(filename) {
try {
const fileContent = await fs.readFile(filename, "utf8")

try {
  const json = JSON.parse(fileContent)

  return json.data
} catch (error) {
  handleJsonError(error)
  return
}

} catch (error) {
handleFileError(error)
return
}
}

// Declares reassignable variables outside the block, which is undesirable
async function readData(filename) {
let fileContent
let json

try {
fileContent = await fs.readFile(filename, "utf8")
} catch (error) {
handleFileError(error)
return
}

try {
json = JSON.parse(fileContent)
} catch (error) {
handleJsonError(error)
return
}

return json.data
}

Good morning.

This is not how I would use "try catch and fetch." In fact, both of the mentioned problems are avoided by properly using "try catch" and the "return" in the appropriate places. Furthermore, in those examples, the code becomes longer with the solution since multiple if statements are required for different errors.

Could you provide a real example of nested try catches that cannot be resolved with a single try catch and where the proposed solution is clearer? It would be helpful to understand the idea.

Thank you very much. Best regards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant