最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to return a 404 HTTP status code when promise resolve to undefined in Nest? - Stack Overflow

matteradmin4PV0评论

In order to avoid boilerplate code (checking for undefined in every controller, over and over again), how can I automatically return a 404 error when the promise in getOne returns undefined?

@Controller('/customers')
export class CustomerController {
  constructor (
      @InjectRepository(Customer) private readonly repository: Repository<Customer>
  ) { }

  @Get('/:id')
  async getOne(@Param('id') id): Promise<Customer|undefined> {
      return this.repository.findOne(id)
         .then(result => {
             if (typeof result === 'undefined') {
                 throw new NotFoundException();
             }

             return result;
         });
  }
}

Nestjs provides an integration with TypeORM and in the example repository is a TypeORM Repository instance.

In order to avoid boilerplate code (checking for undefined in every controller, over and over again), how can I automatically return a 404 error when the promise in getOne returns undefined?

@Controller('/customers')
export class CustomerController {
  constructor (
      @InjectRepository(Customer) private readonly repository: Repository<Customer>
  ) { }

  @Get('/:id')
  async getOne(@Param('id') id): Promise<Customer|undefined> {
      return this.repository.findOne(id)
         .then(result => {
             if (typeof result === 'undefined') {
                 throw new NotFoundException();
             }

             return result;
         });
  }
}

Nestjs provides an integration with TypeORM and in the example repository is a TypeORM Repository instance.

Share Improve this question edited Aug 5, 2018 at 23:36 Kim Kern 60.7k20 gold badges219 silver badges214 bronze badges asked Aug 5, 2018 at 15:52 gremogremo 48.6k80 gold badges272 silver badges447 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You can write an interceptor that throws a NotFoundException on undefined:

@Injectable()
export class NotFoundInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> { {
    // next.handle() is an Observable of the controller's result value
    return next.handle()
      .pipe(tap(data => {
        if (data === undefined) throw new NotFoundException();
      }));
  }
}

Then use the interceptor in your controller. You can use it per class or method:

// Apply the interceptor to *all* endpoints defined in this controller
@Controller('user')
@UseInterceptors(NotFoundInterceptor)
export class UserController {
  

or

// Apply the interceptor only to this endpoint
@Get()
@UseInterceptors(NotFoundInterceptor)
getUser() {
  return Promise.resolve(undefined);
}
Post a comment

comment list (0)

  1. No comments so far