为了避免样板代码(一遍又一遍地检查每个控制器中的未定义),当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
实例。
发布于 2018-08-06 07:36:07
您可以编写在undefined
上抛出NotFoundException
的interceptor
@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();
}));
}
}
然后使用控制器中的拦截器。您可以在每个类或方法中使用它:
// Apply the interceptor to *all* endpoints defined in this controller
@Controller('user')
@UseInterceptors(NotFoundInterceptor)
export class UserController {
或
// Apply the interceptor only to this endpoint
@Get()
@UseInterceptors(NotFoundInterceptor)
getUser() {
return Promise.resolve(undefined);
}
https://stackoverflow.com/questions/51695868
复制相似问题