Custom Errors Javascript

I'm making a differentiation between the errors sent from my API and the errors I'd get from Network issues during a fetch call, so at the moment if my API returns an http error a throw a custom error so I can catch it, is this the best methods, what other methods do you know?
class ResponseError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
class ResponseError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
catch (error) {
if (error instanceof ResponseError) {
throw new Error(error.message);
} else {
console.error(error);
throw new Error("Something went wrong, please try again.");
}
}
catch (error) {
if (error instanceof ResponseError) {
throw new Error(error.message);
} else {
console.error(error);
throw new Error("Something went wrong, please try again.");
}
}
4 Replies
ErickO
ErickOOP3y ago
These are customer facing errors that's why I send the ones from the API which are friendly and any non-API is just a generic message
Zach
Zach3y ago
so you want network error say something went wrong but normal validation error to say validation error?
ErickO
ErickOOP3y ago
oh nvm the validation error part lmao, old code nah all I wanted was a way to throw an error when the API returned a non-200 code but be able to differentiate it from the generic network errors you'd get if your FETCH fails so I can send the actual error message the API returns but not the error message javascript fetch would return as those aren't user friendly so my solution is to create this custom ResponseError and check if the error is an instance of that, if so I know it comes from the API thus the message will be user friendly, otherwise it comes from the fetch and the message will not be friendly so I just send back a generic message
Zach
Zach3y ago
oh well your code looks fine then I don't know of a better way to do whta you want
Want results from more Discord servers?
Add your server