Not dealing with errors properly makes difficult to get readable code. These are a few guidelines on how to properly deal with them.
- If the code calls an external api outside your control, enclose it with a try-catch.
- Think is the error situation is recoverable. (ex: retry, use default values, use cached values)
- Prefer previous validation over try catch
- if you are not to deal with the exception, let it go through and catch it in a global scope.
Use try catch to deal with errors that doesn’t depend on your input to the function call.
try {
fn();
}
catch(e) {
something unexpected happened
}
If the function is part of the class Interface, validate preconditions and throw on missing
If the function is not part of the class Interface(private), validate parameters before calling the function. And take actions.
Allow the exceptions to surface, this serves the purpose the finding errors.
When an exception is thrown a previous validation is missing
Best practices
Don’t
try {
away myAsyncFn()
} catch (e) {
console.log(e);
}
Do
await myAsyncFn().catch(console.error);
Alternative:
Never throw: https://github.com/supermacro/neverthrow
Remove promises errors
async function promHandler
prom: Promise
): Promise<[T | null, any]> {
try {
return [await prom, null];
} catch (error) {
return [null, error];
}
}
const [updated, err] = await promHandler(
update(1, { name: “Mudvayne” }, {})
);
// updated -> {id: 1, name: “Mudvayne”}
// err -> null
const [removed, error] = await promHandler(remove(4, {}));
Remove try catch in synchronous functions
function update(id: number, data: Omit<Note, “id”>, options: Query): Note {
// …
};
function remove(id: number, options: Query): Note {
// …
};
function funcHandler<T extends any[], K>(
func: (…args: T) => K,
…params: T
): [K | null, any] {
try {
return [func(…params), null];
} catch (error) {
return [null, error];
}
}
const [updated, err] = funcHandler(update, 1, { name: “Mudvayne” }, {});
// updated -> {id: 1, name: “Mudvayne”}
// err -> null
const [removed, error] = funcHandler(remove, 6, {});
// removed -> null
// error -> Error “Does not exist.”