-
Notifications
You must be signed in to change notification settings - Fork 0
feat(filter): GraphQL 전용 예외 필터 (P1-3) #117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| import { | ||
| BadRequestException, | ||
| ForbiddenException, | ||
| HttpStatus, | ||
| NotFoundException, | ||
| UnauthorizedException, | ||
| } from '@nestjs/common'; | ||
| import type { ArgumentsHost } from '@nestjs/common'; | ||
| import { GraphQLError } from 'graphql'; | ||
|
|
||
| import { | ||
| GraphQLExceptionFilter, | ||
| mapStatusToCode, | ||
| } from '@/global/filters/graphql-exception.filter'; | ||
| import { CustomLoggerService } from '@/global/logger/custom-logger.service'; | ||
|
|
||
| jest.mock('@/global/logger/logger', () => ({ | ||
| customLogger: { | ||
| info: jest.fn(), | ||
| error: jest.fn(), | ||
| warn: jest.fn(), | ||
| debug: jest.fn(), | ||
| verbose: jest.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| function mockHost( | ||
| fieldName = 'sellerMyStore', | ||
| operation: 'query' | 'mutation' = 'query', | ||
| reqHeaders: Record<string, string> = {}, | ||
| ): ArgumentsHost { | ||
| // GqlArgumentsHost.create(host) reads host.getArgs() — 4-tuple [root, args, context, info] | ||
| const info = { | ||
| fieldName, | ||
| operation: { operation }, | ||
| path: { key: fieldName }, | ||
| parentType: { toString: () => 'Query' }, | ||
| }; | ||
| const context = { | ||
| req: { | ||
| headers: reqHeaders, | ||
| socket: { remoteAddress: '127.0.0.1' }, | ||
| }, | ||
| }; | ||
| return { | ||
| getType: () => 'graphql', | ||
| getArgs: () => [null, {}, context, info], | ||
| getArgByIndex: (i: number) => [null, {}, context, info][i], | ||
| switchToHttp: () => ({}), | ||
| switchToRpc: () => ({}), | ||
| switchToWs: () => ({}), | ||
| } as unknown as ArgumentsHost; | ||
| } | ||
|
|
||
| describe('GraphQLExceptionFilter', () => { | ||
| let filter: GraphQLExceptionFilter; | ||
| let logger: CustomLoggerService; | ||
|
|
||
| beforeEach(() => { | ||
| logger = new CustomLoggerService(); | ||
| logger.txError = jest.fn(); | ||
| filter = new GraphQLExceptionFilter(logger); | ||
| }); | ||
|
|
||
| describe('mapStatusToCode', () => { | ||
| it.each([ | ||
| [HttpStatus.BAD_REQUEST, 'BAD_USER_INPUT'], | ||
| [HttpStatus.UNAUTHORIZED, 'UNAUTHENTICATED'], | ||
| [HttpStatus.FORBIDDEN, 'FORBIDDEN'], | ||
| [HttpStatus.NOT_FOUND, 'NOT_FOUND'], | ||
| [HttpStatus.INTERNAL_SERVER_ERROR, 'INTERNAL_SERVER_ERROR'], | ||
| [418, 'INTERNAL_SERVER_ERROR'], | ||
| ])('%i → %s', (status, expected) => { | ||
| expect(mapStatusToCode(status)).toBe(expected); | ||
| }); | ||
| }); | ||
|
|
||
| describe('format', () => { | ||
| it.each([ | ||
| [ | ||
| new BadRequestException('bad input'), | ||
| 400, | ||
| 'BAD_USER_INPUT', | ||
| 'bad input', | ||
| ], | ||
| [ | ||
| new UnauthorizedException('no token'), | ||
| 401, | ||
| 'UNAUTHENTICATED', | ||
| 'no token', | ||
| ], | ||
| [new ForbiddenException('nope'), 403, 'FORBIDDEN', 'nope'], | ||
| [new NotFoundException('missing'), 404, 'NOT_FOUND', 'missing'], | ||
| ])( | ||
| '%p → statusCode=%i, code=%s, message=%s', | ||
| (exception, status, code, message) => { | ||
| const host = mockHost(); | ||
| const result = filter.format(exception, host); | ||
|
|
||
| expect(result).toBeInstanceOf(GraphQLError); | ||
| expect(result.message).toBe(message); | ||
| expect(result.extensions).toEqual( | ||
| expect.objectContaining({ | ||
| code, | ||
| statusCode: status, | ||
| operation: 'query', | ||
| fieldName: 'sellerMyStore', | ||
| }), | ||
| ); | ||
| }, | ||
| ); | ||
|
|
||
| it('일반 Error 는 INTERNAL_SERVER_ERROR (500) 으로 매핑된다', () => { | ||
| const host = mockHost(); | ||
| const result = filter.format(new Error('boom'), host); | ||
|
|
||
| expect(result.extensions).toEqual( | ||
| expect.objectContaining({ | ||
| code: 'INTERNAL_SERVER_ERROR', | ||
| statusCode: 500, | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('Error 가 아닌 throw (예: string) 도 INTERNAL_SERVER_ERROR 로 안전하게 매핑된다', () => { | ||
| // stack 추출 분기에서 exception !instanceof Error 경로 커버 | ||
| const host = mockHost(); | ||
| const result = filter.format('plain string thrown', host); | ||
|
|
||
| expect(result.extensions).toEqual( | ||
| expect.objectContaining({ | ||
| code: 'INTERNAL_SERVER_ERROR', | ||
| statusCode: 500, | ||
| }), | ||
| ); | ||
| // resolveMessage 가 fallback 'Internal Server Error' 반환 | ||
| expect(result.message).toBe('Internal Server Error'); | ||
| }); | ||
|
|
||
| it('extensions.requestId 에 incoming x-request-id 를 사용한다', () => { | ||
| const host = mockHost('sellerProducts', 'query', { | ||
| 'x-request-id': 'req-abc-123', | ||
| }); | ||
| const result = filter.format(new BadRequestException('x'), host); | ||
|
|
||
| expect(result.extensions?.requestId).toBe('req-abc-123'); | ||
| }); | ||
|
|
||
| it('x-request-id 가 없으면 새 requestId 가 생성된다 (UUID 형태)', () => { | ||
| const host = mockHost(); | ||
| const result = filter.format(new BadRequestException('x'), host); | ||
|
|
||
| expect(typeof result.extensions?.requestId).toBe('string'); | ||
| expect( | ||
| (result.extensions?.requestId as string).length, | ||
| ).toBeGreaterThanOrEqual(8); | ||
| }); | ||
|
|
||
| it('mutation operation 도 정확히 반영된다', () => { | ||
| const host = mockHost('sellerCreateProduct', 'mutation'); | ||
| const result = filter.format(new BadRequestException('x'), host); | ||
|
|
||
| expect(result.extensions).toEqual( | ||
| expect.objectContaining({ | ||
| operation: 'mutation', | ||
| fieldName: 'sellerCreateProduct', | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('txError 로 구조화 로그를 남긴다', () => { | ||
| const host = mockHost('sellerProducts'); | ||
| filter.format(new BadRequestException('bad'), host); | ||
|
|
||
| expect(logger.txError).toHaveBeenCalledTimes(1); | ||
| expect(logger.txError).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| error: expect.objectContaining({ statusCode: 400, message: 'bad' }), | ||
| }), | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import { ArgumentsHost, HttpStatus, Injectable } from '@nestjs/common'; | ||
| import { GqlArgumentsHost } from '@nestjs/graphql'; | ||
| import type { Request } from 'express'; | ||
| import { GraphQLError, type GraphQLResolveInfo } from 'graphql'; | ||
|
|
||
| import { resolveMessage, resolveStatus } from '@/common/helpers/error.helper'; | ||
| import { | ||
| buildGraphqlRequestMeta, | ||
| calculateDuration, | ||
| ensureRequestTracking, | ||
| resolveUserId, | ||
| } from '@/common/utils/request-context'; | ||
| import { CustomLoggerService } from '@/global/logger/custom-logger.service'; | ||
| import { LogContext } from '@/global/types/log.type'; | ||
|
|
||
| /** | ||
| * HTTP status code → GraphQL extensions.code 매핑. | ||
| * Apollo 권장 표준 코드를 따른다. 알 수 없는 status 는 INTERNAL_SERVER_ERROR. | ||
| */ | ||
| const STATUS_TO_CODE: Record<number, string> = { | ||
| [HttpStatus.BAD_REQUEST]: 'BAD_USER_INPUT', | ||
| [HttpStatus.UNAUTHORIZED]: 'UNAUTHENTICATED', | ||
| [HttpStatus.FORBIDDEN]: 'FORBIDDEN', | ||
| [HttpStatus.NOT_FOUND]: 'NOT_FOUND', | ||
| }; | ||
|
|
||
| export function mapStatusToCode(status: number): string { | ||
| return STATUS_TO_CODE[status] ?? 'INTERNAL_SERVER_ERROR'; | ||
| } | ||
|
|
||
| /** | ||
| * GraphQL 컨텍스트 전용 예외 포맷터. | ||
| * | ||
| * NestJS 글로벌 필터는 host type 별로 1 회만 매칭되므로 별도 글로벌 등록 대신 | ||
| * `HttpExceptionFilter` 가 graphql context 일 때 본 클래스에 위임한다. | ||
| * | ||
| * extensions: | ||
| * - code : BAD_USER_INPUT / UNAUTHENTICATED / FORBIDDEN / NOT_FOUND / INTERNAL_SERVER_ERROR | ||
| * - statusCode : 400 / 401 / 403 / 404 / 500 | ||
| * - requestId : x-request-id (트래킹용) | ||
| * - operation : query / mutation / subscription | ||
| * - fieldName : 루트 필드명 | ||
| */ | ||
| @Injectable() | ||
| export class GraphQLExceptionFilter { | ||
| constructor(private readonly logger: CustomLoggerService) {} | ||
|
|
||
| format(exception: unknown, host: ArgumentsHost): GraphQLError { | ||
| const gqlHost = GqlArgumentsHost.create(host); | ||
| const info = gqlHost.getInfo<GraphQLResolveInfo>(); | ||
| const ctx = gqlHost.getContext<{ req: Request }>(); | ||
| const req = ctx.req; | ||
|
|
||
| const { requestId, startTime } = ensureRequestTracking(req); | ||
| const userId = resolveUserId(req); | ||
| const gqlRequest = buildGraphqlRequestMeta(info, req); | ||
|
|
||
| const status = resolveStatus(exception); | ||
| const message = resolveMessage(exception); | ||
| const stack = exception instanceof Error ? exception.stack : undefined; | ||
| const duration = calculateDuration(startTime); | ||
|
|
||
| this.logger.txError({ | ||
| userId, | ||
| requestId, | ||
| request: gqlRequest, | ||
| error: { statusCode: status, message, stack }, | ||
| processingTimeInMs: duration, | ||
| context: LogContext.GRAPHQL, | ||
| }); | ||
|
|
||
| return new GraphQLError(message, { | ||
| extensions: { | ||
| code: mapStatusToCode(status), | ||
| statusCode: status, | ||
| requestId, | ||
| operation: info.operation.operation, | ||
| fieldName: info.fieldName, | ||
| }, | ||
| }); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For GraphQL errors thrown from resolvers/services, the globally registered
GqlLoggingInterceptoralready records atxErrorin itstap.errorpath before rethrowing, and then this filter records anothertxErrorfor the same request/error here. That means ordinary resolver failures will produce duplicate transaction-error logs with the same requestId/field, which can inflate error counts and confuse alerting; either the interceptor or this filter should own error logging for that path.Useful? React with 👍 / 👎.