1.创建文件夹 response
2.成功获取数据 包装
(1)创建 successResponse.ts文件 并添加如下代码
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';
interface Data<T> {
data: T;
}
@Injectable()
export class SuccessResponse<T> implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<Data<T>> {
return next.handle().pipe(
map((data) => {
return {
code: 1,
data, // data为你操作返回的数据
message: '操作成功',
success: true,
};
}),
);
}
}
(2)在main.ts中引入如下代码
app.useGlobalInterceptors(new SuccessResponse());
2.失败包装
(1)在response下创建 failResponse.ts文件
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
} from '@nestjs/common';
import { Response, Request } from 'express';
@Catch()
// 接口异常拦截器
export class HttpFaild implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const request = ctx.getRequest<Request>();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
console.log(status, 'status');
response.status(status).json({
msg: exception.message,
code: 2,
});
}
}
(2)在main.ts中引入如下代码
app.useGlobalFilters(new HttpFaild());
(3)使用
throw new HttpException('数据获取出错', HttpStatus.FORBIDDEN);
Comments NOTHING