当承诺在 Nest 中解析为未定义时,如何 return 404 HTTP 状态代码?
How to return a 404 HTTP status code when promise resolve to undefined in Nest?
为了避免样板代码(一遍又一遍地检查每个控制器中的未定义),当 getOne
[=18= 中的承诺时,我如何自动 return 出现 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
实例。
你可以写一个 interceptor 在 undefined
上抛出 NotFoundException
:
@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();
}));
}
}
然后在你的控制器中使用拦截器。您可以按照 class 或方法使用它:
// 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);
}
为了避免样板代码(一遍又一遍地检查每个控制器中的未定义),当 getOne
[=18= 中的承诺时,我如何自动 return 出现 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
实例。
你可以写一个 interceptor 在 undefined
上抛出 NotFoundException
:
@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();
}));
}
}
然后在你的控制器中使用拦截器。您可以按照 class 或方法使用它:
// 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);
}