注:この記事は、nestjsを初めて学習した後のブロガーの知識と理解のみを記録しています。経験はまだ浅く、記事の内容は参照用です。エラーがあれば訂正してください。
1つ:側面として
この記事では一時的に詳細については説明しません
1.アスペクトタイプ:ExceptionFilterインターフェイス実装クラス
2.アスペクト入力
HttpException例外オブジェクト
ArgumentsHostパラメーターホストオブジェクト
3.アスペクト出力:異常応答を構築します
4.使用シナリオの側面
- 例外処理
例外処理
組み込みの例外レイヤーは、アプリケーション全体でスローされたすべての例外を処理する役割を果たします。未処理の例外がキャッチされると、エンドユーザーはわかりやすい応答を受け取ります。
1.処理なし
- グローバルキャプチャ後に返される応答構造
{
"statusCode": 500,
"message": "Internal server error"
}
2.一般的な需要処理
- 手動で投げる
// 方式1:直接抛出HttpException,异常信息为forbidden
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
// 方式2:直接抛出HttpException,异常信息为object
throw new HttpException({
status: HttpStatus.FORBIDDEN,
error: 'This is a custom message',
}, HttpStatus.FORBIDDEN);
// 方式3:抛出HttpException子类(内置异常/自定义异常)
throw new UnAuthenticationException();
// 自定义异常类UnAuthenticationException
// export class UnAuthenticationException extends HttpException {
// constructor() {
// super('not authentication', 30000);
// }
// }
- グローバルキャプチャ後に返される応答構造
// 方式1
{
"statusCode": 403,
"message": "Forbidden"
}
// 方式2
{
"status": 403,
"error": "This is a custom message"
}
// 方式3
{
"statusCode": 30000,
"message": "not authentication"
}
3.複雑な需要処理
特定の応答が例外によってキャプチャされる前に、aopアスペクト処理(ロギングなど)を追加する必要がある場合は、例外フィルターを追加することで実現できます。
手動スロー(この側面に注意を払わないでください)
例外フィルターキャプチャ
- 例外フィルターの定義
import {
ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import {
Request, Response } from 'express';
@Catch(HttpException)// @Catch()会捕获不经手动抛出的异常(即第一种不作处理的异常)
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,
});
}
}
// 另一种:继承式全局异常过滤器
- 例外フィルターバインディング
@Post()
@UseFilters(HttpExceptionFilter) // 通过@UseFilters这个装饰器,使被装饰的方法绑定HttpExceptionFilter这个异常过滤器
async create(@Body() createCatDto: CreateCatDto) {
throw new ForbiddenException();
}
// 另一种:也可绑定为全局/模块异常过滤器
グローバルキャプチャ後に返される応答構造
{
statusCode: 'status:xxx',
timestamp: 'date:xxx',
path: 'url:xxx',
}