I have a MERN Application and I am making API calls in the frontend using axios.
For example:
// user is an object with properties email and password
const res = await axiosInstance.post("/admin/sign-in", {
email: user.email,
password: user.password,
});
If the API call fails (for whatever reason) I get an error, so is it a good idea to always make API calls in a try-catch block. If not, what is the recommended way of doing so? I know it is possible to check the response status, but is it an improper practice to use try-catch? The status check does not work in case the server is down.
try {
const res = await axiosInstance.post("/admin/sign-in", {
email: user.email,
password: user.password,
});
} catch (error) {
console.log(error);
}
Similarly, on the backend side, should I handle all requests and responses in a try-catch block so that an accidental (or deliberate ๐) misplaced JSON token in the request does not cause an error that shuts down the server?
Thank you.
I prefer to throw typed errors from my handlers, and not catch them there; Either an internal system error or and API error with a message for the client.
Then I catch the error higher up in the stack, in the default error handler, sending an API message to the user, and/or logging the system message internally for internal errors, depending on the error type. This way I can catch all errors as well, eliminating boilerplate code.
This also allows me to consolidate, and control what gets sent to the client.