Errors are part of your API
"Something went wrong" helps nobody. Good errors say what kind of problem happened and keep the original cause, so the code that catches them can react properly — retry a network error, show a form message for a validation error.
Custom error classes
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function signUp(email) {
if (!email.includes("@")) throw new ValidationError("email", "That email looks incomplete");
return "ok";
}
try {
signUp("ashaexample.com");
} catch (err) {
if (err instanceof ValidationError) console.log(`${err.field}: ${err.message}`);
else throw err;
}