Monday 22 July 2019

Best way to write this signup handler and gracefully handle errors?

I'm writing an application with Koa and Objection. I wrote the following code for the signup.(routes file) router.post('/signup', async (ctx) => { try { const user = await userService.Signup(ctx.request.body); ctx.status = 201; ctx.body = user; } catch(err){ ctx.status = err.statusCode || err.status || 500; ctx.body = { message: 'Failed to create user.' }; } });(service file) async Signup(userInfo){ let {username, password} = userInfo; try{ password = await argon2.hash(password); const userRecord = await User.query().insert({username: username, password: password}).pick(['id', 'username']); if (!userRecord){ throw new Error('Could not create user.'); } return userRecord; } catch(err){ throw err; } } I was curious if somebody had any critiques on this implimentation. Also, could somebody point in the right direction for error handling? For example, sending errors like "username already taken".

Submitted July 22, 2019 at 11:09PM by AmateurLlama

No comments:

Post a Comment