Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code snippet to throw an error for Null or Undefined
/**
* Code snippet to throw an error for Null or Undefined
* Container = object containing variables for example
* if we want to assert that a variable x is not null or undefined
* we can use function like this
* let x;
* assertNonNull({x}) // if x is null or undefined,
* this function will throw appropriate error
*/
export const assertNonNull = (container: any) => {
const entries = Object.entries(container);
let error = '';
const getErrorMessage = (variable: string, token: string) =>
`${variable} should not be ${token}`;
const addError = (errorString: string) => (error += errorString);
for (let i = 0; i < entries.length; i++) {
let [key, value] = entries[i];
if (value === null) {
addError(getErrorMessage(key, 'null'));
}
if (value === undefined) {
addError(getErrorMessage(key, 'undefined'));
}
}
if (error.length > 0) {
throw new Error(error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment