当承诺在 Nest 中解析为 undefined 时,如何返回 404 HTTP 状态代码? [英] How to return a 404 HTTP status code when promise resolve to undefined in Nest?
问题描述
为了避免样板代码(一遍又一遍地检查每个控制器中的 undefined),当 getOne
中的 promise 返回 undefined 时,如何自动返回 404 错误?
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 提供了与 TypeORM 的集成,在示例存储库中是一个 TypeORM Repository
实例.
Nestjs provides an integration with TypeORM and in the example repository is a TypeORM Repository
instance.
推荐答案
您可以编写一个拦截器在 undefined
上抛出 NotFoundException
:
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 {
或
// Apply the interceptor only to this endpoint
@Get()
@UseInterceptors(NotFoundInterceptor)
getUser() {
return Promise.resolve(undefined);
}
这篇关于当承诺在 Nest 中解析为 undefined 时,如何返回 404 HTTP 状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!