【发布时间】:2020-10-21 14:18:38
【问题描述】:
当我看到以下代码时,
https://github.com/nestjs/nest/tree/master/packages/common
例如ArgumentsHost是由接口定义的。
但是方法的内容好像没有定义。
* @publicApi
*/
export interface ArgumentsHost {
/**
* Returns the array of arguments being passed to the handler.
*/
getArgs<T extends Array<any> = any[]>(): T;
/**
* Returns a particular argument by index.
* @param index index of argument to retrieve
*/
getArgByIndex<T = any>(index: number): T;
/**
* Switch context to RPC.
* @returns interface with methods to retrieve RPC arguments
*/
switchToRpc(): RpcArgumentsHost;
/**
* Switch context to HTTP.
* @returns interface with methods to retrieve HTTP arguments
*/
switchToHttp(): HttpArgumentsHost;
/**
* Switch context to WebSockets.
* @returns interface with methods to retrieve WebSockets arguments
*/
switchToWs(): WsArgumentsHost;
/**
* Returns the current execution context type (string)
*/
getType<TContext extends string = ContextType>(): TContext;
}
但是当我看到以下说明时,
https://docs.nestjs.com/exception-filters
ArgumentsHost 被使用,switchToHttp() 运行良好。
为什么这些方法在没有特定定义的情况下有效?
我错过了大问题吗?由于我是初学者,如果有人有意见,请告诉我。
谢谢
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
【问题讨论】:
标签: typescript nestjs