I have the following code, simplified to leave out unnecessaries:
try {
const response = await axios.put(url, {});
if ( response.status === 200 ) {
MicroService.action(data);
}
} catch ( error ) {
// user is not signed in, so send to create-account/sign-in
if (error.status === 401) {
MicroService.otherAction(data);
} else {
console.error(`The server returned an unexpected ${error.status} error upon attempting to hit ${url}`);
}
}
The problem is that the catch
clause also catches any error that occurs in the fourth line, MicroService.action(data)
. I only want to catch an error with the axios call on line 2, no other error should be silenced.
But if I take the MicroService.action(data)
and move it to after the catch
, then it happens even if the try
fails, which is wrong. It should only happen if the try
succeeds.
I could set a variable in the try
clause, e.g. if (response.status === 200) let success = true;
, and then check that variable after the catch
clause. But that feels messy and inelegant for anything but the simplest possible case.
Is there a better way of doing this?