$ nest g filter filter/http-exception
$ nest g filter filter/any-exception
http-exception.filter.ts: 捕获主动刨错的内容
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();
// 设置错误信息
const message = exception.message
? exception.message
: `${status >= 500 ? "Service Error" : "Client Error"}`;
const errorResponse = {
data: {},
message: status == 401 ? "请重新登陆" : message,
code: status == 401 ? 401 : -1,
};
// 设置返回的状态码, 请求头,发送错误信息
response.status(status);
response.header("Content-Type", "application/json; charset=utf-8");
response.send(errorResponse);
}
}
any-exception.filter: 捕获全部错误
/**
* 捕获所有异常
*/
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from "@nestjs/common";
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
response.status(status).json({
statusCode: status,
msg: `Service Error: ${exception}`,
});
}
}
$ nest g interceptor interceptor/transform
transform.interceptor.ts: 格式化返回体
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { Logger } from "../utils/log4js";
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.getArgByIndex(1).req;
return next.handle().pipe(
map((data) => {
return {
data,
code: 1,
msg: "请求成功",
};
})
);
}
}
const app = await NestFactory.create(AppModule);
...
//格式化 返回体
app.useGlobalInterceptors(new TransformInterceptor());
// 过滤处理 HTTP 异常
app.useGlobalFilters(new AllExceptionsFilter());
app.useGlobalFilters(new HttpExceptionFilter());
...
await app.listen(listenPort);
if (!userInfo) {
throw new HttpException("用户不存在", 403);
}