So, in the process of creating a user there are 4 possible outcomes:
-
Username is already taken
-
Email is already taken
- Username is invalid
- Email is invalid
Here is what I have in the controller for now:
const user = await this.addUserService.add(username, email, password)
if (user) {
return {
statusCode: 201,
body: user
}
} else {
return {
statusCode: 400,
body: // ???
}
}
The thing is, what should the addUserService
return if the username/email is invalid or in use?
I am thinking about creating different error types, such as InvalidParamsError
, ParamInUseError
and share them between the UserController
and UserService
.
So I would have something like this:
const result = await this.addUserService.add(username, email, password)
if (typeof result === InvalidParamsError || typeof result === ParamInUseError) {
return {
statusCode: 401,
body: result.message
}
} else { // then we assume user has been created
return {
statusCode: 201,
body: 'User created!'
}
}
Is it okay to share these Error classes between the controller and the service? If not, or even if it’s okay, is there a better way to handle errors when the outcome is not a simple true
or false
?
Thanks.
Go to Source
Author: kibe