首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当promise resolve在Nest中未定义时,如何返回404 HTTP状态码?

当promise resolve在Nest中未定义时,如何返回404 HTTP状态码?
EN

Stack Overflow用户
提问于 2018-08-05 23:52:24
回答 1查看 2.1K关注 0票数 6

为了避免样板代码(一遍又一遍地检查每个控制器中的未定义),当getOne中的promise返回未定义时,我如何自动返回404错误?

代码语言:javascript
复制
@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提供了与TypeORM的集成,在示例存储库中是一个TypeORM Repository实例。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-06 07:36:07

您可以编写在undefined上抛出NotFoundExceptioninterceptor

代码语言:javascript
复制
@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();
      }));
  }
}

然后使用控制器中的拦截器。您可以在每个类或方法中使用它:

代码语言:javascript
复制
// Apply the interceptor to *all* endpoints defined in this controller
@Controller('user')
@UseInterceptors(NotFoundInterceptor)
export class UserController {

代码语言:javascript
复制
// Apply the interceptor only to this endpoint
@Get()
@UseInterceptors(NotFoundInterceptor)
getUser() {
  return Promise.resolve(undefined);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51695868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档