当承诺在Nest中解析为undefined时,如何返回404 HTTP状态代码?

时间:2018-08-05 15:52:24

标签: javascript node.js nestjs typeorm

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

@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实例。

1 个答案:

答案 0 :(得分:1)

您可以编写一个interceptor并在def getMonth(month): try: list_of_month_index0 = ['Jan', 'Feb','March','April','May','June','July','Aug','Sep','Oct','Nov','Dec'] if month < 1 or month > len(list_of_month_index0): return 'ERROR: out of range!' return list_of_month_index0[month - 1] except: return 'ERROR: invalid number!' 上抛出一个NotFoundException

undefined

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

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

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