Vlad
Vlad

Reputation: 337

Throw HttpException at service in nestjs

Is it good way to throw Http Exeption at service in nestjs? What is the best way to processing error at service in nestjs?

Upvotes: 9

Views: 5062

Answers (2)

fizban
fizban

Reputation: 59

To elaborate on this answer, https://stackoverflow.com/a/73211663/1500042, you can use it to automatically configure http codes:

my.controller.ts:

@Get()
async getIt(@Req() req) {
try {
  return await this.myService.getThe(req.thing);
} catch (error) {
  throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
}

This sends a '400' response and blames the user (as you do). As a bonus it resists crashing on bad requests.

Upvotes: 1

From experience, it's best practice to throw HTTPExceptions in the controller logic manually or have an exception filter automatically catch exceptions. Services should be reusable pieces of functionality that can sometimes be used in non-http contexts.

Having http logic in the service layer feels like an anti-pattern.

Upvotes: 12

Related Questions