http-exception.filter.ts
nest.js/02-intermediate/code/common/filters/http-exception.filter.ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message =
exception instanceof HttpException
? exception.getResponse()
: 'Internal server error';
response.status(status).json({
success: false,
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
message: typeof message === 'string' ? message : (message as any).message || message,
});
}
}
관련 글
app.controller.ts
app.controller.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.controller.ts).
글 읽기 →app.module.ts
app.module.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.module.ts).
글 읽기 →app.service.ts
app.service.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.service.ts).
글 읽기 →main.ts
main.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/main.ts).
글 읽기 →todos.controller.ts
todos.controller.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/todos/todos.controller.ts).
글 읽기 →todos.module.ts
todos.module.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/todos/todos.module.ts).
글 읽기 →