I have a control that calls a service. If the service returns an empty payload from the db I want to throw an exception.
at the moment I am doing that in the service: this is the service I have at the moment with the exception.
async getPreferences(eUserId: string): Promise<UserPreferences> {
const userPreferences = await this.userPreferencesModel.findOne({
eUserId,
});
if (!userPreferences) {
throw new NotFoundException("We couldn't find your user preferences");
}
return userPreferences;
}
I want the controller to handle the exception, The issue is that the controller response is a Promise. How can I handle that?
This is what I shave done:
@Get()
async getPreferences(
@Headers('x-e-user-id') eUserId: string,
): Promise<UserPreferences> {
const userPreferences = this.userPreferencesService.getPreferences(eUserId);
console.log('userPreferences: ', userPreferences);
// Here is what I am trying to monitor...
if (userPreferences) {
throw new NotFoundException("We couldn't find your user preferences");
}
return userPreferences;
}
Ther console.log in the controller returns:
userPreferences: Promise { <pending> }
Now, if the service response is empty no exception is thrown.
How can I monitor the service result in order to throw an exception
CodePudding user response:
Multiple ways you can solve this. Here's one.
Don't throw an error in your service, just return the result or null
.
async getPreferences(eUserId: string): Promise<UserPreferences | null> {
return this.userPreferencesModel.findOne({
eUserId,
});
}
Then in your controller await
for the result, you forgot this. That's why you are seeing a pending promise. After the result has been resolved, check if any user preferences were returned and throw the NotFoundException
if not.
@Get()
async getPreferences(@Headers('x-e-user-id') eUserId: string): Promise<UserPreferences> {
const userPreferences = await this.userPreferencesService.getPreferences(eUserId);
if (!userPreferences) {
throw new NotFoundException("We couldn't find your user preferences");
}
return userPreferences;
}
I would not throw NotFoundException
or any other HTTP related error from your service. Leave that responsibility up to your controller, don't tie your service (logic) to HTTP error codes. Throw errors here that are not aware of the context (HTTP) they are being used in.
PS: You might also consider passing the user ID via the query string or as a route parameter instead of via the headers.