1116
工作
反思
任务
今日算法
今日学习:
今日复习:
好文推荐
有感好文
之前学习 Nest.js 的时候卡在了一个地方:响应体拦截
- 拦截错误请求
bash
nest g filter core/filter/http-exception
- 过滤器代码实现:
js
import {ArgumentsHost,Catch, ExceptionFilter, HttpException} from '@nestjs/common';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp(); // 获取请求上下文
const response = ctx.getResponse(); // 获取请求上下文中的 response对象
const status = exception.getStatus(); // 获取异常状态码
// 设置错误信息
const message = exception.message
? exception.message
: `${status >= 500 ? 'Service Error' : 'Client Error'}`;
const errorResponse = {
data: {},
message: message,
code: -1,
};
// 设置返回的状态码, 请求头,发送错误信息
response.status(status);
response.header('Content-Type', 'application/json; charset=utf-8');
response.send(errorResponse);
}
}
最后需要在main.ts中全局注册
js
...
import { HttpExceptionFilter } from './core/filter/http-exception.filter';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
...
// 注册全局错误的过滤器
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(9080);
}
bootstrap();
这样对请求错误就可以统一的返回了,返回请求错误只需要抛出异常即可,比如之前的:
js
throw new HttpException('文章已存在', 401);
接下来对请求成功返回的格式进行统一的处理,可以用 Nest.js的拦截器来实现。
- 创建拦截器
bash
nest g interceptor core/interceptor/transform
- 拦截器代码实现:
js
import {CallHandler, ExecutionContext, Injectable,NestInterceptor,} from '@nestjs/common';
import { map, Observable } from 'rxjs';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((data) => {
return {
data,
code: 0,
msg: '请求成功',
};
}),
);
}
}
最后和过滤器一样,在main.ts中全局注册:
js
...
import { TransformInterceptor } from './core/interceptor/transform.interceptor';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
...
// 全局注册拦截器
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(9080);
}
bootstrap();
项目推荐
值得学习的项目
- 推荐一款基于nodejs+koa+vue开发的开源智慧物业系统 包括后台和小程序等多端应用,非常值得深入学习!