I am working with node.js and Graphql without Express, to validate the input i use Joi, so in my mutation resolver i did this:
async user(_, { input }, { dataSources }) {
if (process.env.NODE_ENV === 'development') {
debug(input);
}
// Validation
if (input.role === 'user') {
debug('validate user creation schema');
validate(userSchemas.userRegisterSchema.post, input);
} else if (input.role === 'pro') {
debug('validate pro creation schema');
validate(userSchemas.userProRegisterSchema);
} else {
throw new Error('Bad input error');
}
so this is the code in the validate function folder:
import Debug from 'debug';
import BadInputError from '../errors/BadInputError.js';
/*
* validate module.
* @module validate
*/
const debug = Debug(`${process.env.DEBUG_MODULE}:validation`);
// function to validate the input data
async function validate(schema, inputData) {
try {
debug('validate input data');
await schema.validateAsync(inputData);
} catch (error) {
debug('validation error');
throw new BadInputError(error);
}
}
export default validate;
And when entry is wrong i have the error but server crash, i don't want server crash... Have you an idea please? thank you
i try a lot of things, with return and some idea of IA but nothing good.
You don't need to throw error from else condition.
this error do not have any handling when the promise is rejected. you can also use unhandledRejection event at process level if required. https://nodejs.org/api/process.html#event-unhandledrejection
or else just log using your logger.