Hey there, I'm currently working on implementing a custom error handling feature in my application. An example scenario is when a user tries to create an account with an email that already exists:
{
"errors": [
{
"message": "The email exists",
"statusCode": "400"
}
],
"data": null
}
Here's what I have so far:
my APP.TS:
export async function startServer() {
const app = express();
const schema = await createSchema();
useContainer(Container);
const connection = await createConnection();
const server = new ApolloServer({
schema,
context: ({ req, res }: any) => ({ req, res }),
});
server.applyMiddleware({ app });
return app;
}
Resovler.TS:
@Resolver()
export class CreateUserResolver {
//dependency inject
constructor(private readonly userService: UserService) {}
//create User Mutaton
@Mutation(() => User)
async register(
@Arg('data')
data: RegisterInput,
): Promise<Partial<User> | Object> {
const user = this.userService.findOrCreate(data);
return user;
}
}
Input:
@InputType()
export class RegisterInput {
@Field()
@IsEmail({}, { message: 'Invalid email' })
email: string;
@Field()
@Length(1, 255)
name: string;
@Field()
password: string;
}
Service:
constructor(
@InjectRepository(User)
private userRep: Repository<User>,
) {}
async findOrCreate(data: Partial<User>): Promise<Partial<User> | Object> {
let user = await this.userRep.findOne({ where: { email: data.email } });
if (user) throw new Error('user already exists');
data.password = await bcrypt.hash(data.password, 12);
user = await this.userRep.save({
...data,
});
return user;
}
Currently, my workaround is to simply use:
if (user) throw new Error ('user already exists');
However, I'm struggling to figure out how I could incorporate the status code or return only the error message without all the additional information: