사용자 노출 에러 메시지 안전화 및 코드 기반 처리 표준화 - #310
Conversation
|
Warning Review limit reached
Next review available in: 48 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (26)
📝 WalkthroughWalkthroughBackend HTTP, WebSocket, and authentication errors now use standardized safe codes, messages, and request IDs. Frontend API, toast, Sentry, and socket handling now consume error codes instead of raw messages, with expanded unit-test coverage. ChangesBackend error normalization
Frontend error handling
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Backend
participant FrontendAPI
participant ErrorHandler
participant Toast
participant Sentry
Backend->>FrontendAPI: safe error with code and requestId
FrontendAPI->>ErrorHandler: createApiError(response)
ErrorHandler->>Toast: show mapped user message
FrontendAPI->>Sentry: captureSystemError(error, source)
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
- 전역 HTTP 예외 응답 구조 통일 - code, message, requestId 기반 에러 페이로드 표준화 - 알 수 없는 예외 및 5xx 에러의 공통 메시지 치환 - 응답 본문 내 raw details, stack, 내부 예외 원문 제거 - 로그 상 원본 예외 및 추적 정보 유지 - 전역 예외 필터 단위 테스트 추가
- 인증 복구 동작 구분을 위한 세부 에러 코드 유지 - Access Token 만료 및 유효성 오류 구분 - Refresh Token 만료, 누락, 재사용 오류 구분 - 세션 종료 및 재로그인 대상 오류 구분 유지 - 인증 코드별 안전한 사용자 메시지 중앙 관리 - 내부 인증 실패 사유의 로그 추적 정보 유지 - 인증 예외 및 JWT 가드 단위 테스트 추가
- 에러 코드별 안전한 사용자 메시지 중앙 관리 - 알 수 없는 에러 코드의 공통 메시지 치환 - raw error message 직접 노출 방지 - 인증 재발급 및 로그아웃 분류 동작 유지 - API 에러 내 원본 메시지 및 requestId 추적 정보 유지 - 백엔드 표준 에러 응답 타입 반영 - 에러 메시지 매핑 단위 테스트 추가
- 시스템 오류 토스트 공통 함수 도입 - 전역 Query 및 Mutation 오류 처리 경로 통일 - 개별 시스템 오류 토스트의 코드 매핑 적용 - raw error message 토스트 전달 방지 - 폼 검증 및 도메인 안내 문구 처리 유지 - 토스트 메시지 및 옵션 전달 단위 테스트 추가
- 공동 드래프트 조회 오류의 code 기반 판별 - raw error message 문자열 비교 제거 - 타입 안전한 에러 코드 판별 함수 추가 - 게시 발행 오류 코드 상수 중복 제거 - 기존 NOT_FOUND 처리 및 Sentry 분기 유지 - 에러 코드 판별 단위 테스트 추가
- WebSocket 예외의 code, message, requestId 응답 표준화 - 알 수 없는 WS 예외의 raw 메시지 노출 차단 - 인증 오류의 토큰 재발급 동작 유지 - 드래프트 인원 초과 안내 동작 유지 - validation, 권한, stale 이벤트 무시 정책 유지 - 예상하지 못한 WS 오류의 Sentry 추적 유지 - 백엔드 필터 및 프론트 오류 정책 단위 테스트 추가
- 전역 Query 및 Mutation 시스템 오류 Sentry 보고 - Sentry 이벤트 내 requestId 및 errorCode 태그 추가 - 예상 가능한 사용자 오류 보고 제외 - 네트워크 및 파싱 오류 중복 보고 방지 - 기존 토스트와 재시도 동작 유지 - Sentry 보고 정책 단위 테스트 추가
afdb228 to
860b82f
Compare
Coverage Report for Backend (backend)
File Coverage
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
frontend/src/store/useSocketStore.ts (1)
104-125: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winGuard the report path against malformed socket payloads.
data?.codesafely classifies a missing payload asREPORT, but Line 120 then dereferencesdata.code, throwing instead of reporting it.Proposed fix
socket.on('exception', async (data: SocketExceptionResponse) => { const action = getSocketErrorAction(data?.code); + const errorCode = data?.code ?? 'UNKNOWN_SOCKET_ERROR'; if (action === SOCKET_ERROR_ACTIONS.SHOW_DRAFT_FULL) { toast.warning('참여 인원이 가득 찼어요.'); return; } @@ - Sentry.captureMessage(`소켓 서버 예외: ${data.code}`, { + Sentry.captureMessage(`소켓 서버 예외: ${errorCode}`, {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@frontend/src/store/useSocketStore.ts` around lines 104 - 125, Update the unexpected-error reporting block in the socket exception handler to safely handle missing or malformed data, avoiding the direct data.code dereference used by Sentry.captureMessage. Preserve classification via getSocketErrorAction(data?.code) and ensure the report/log path still records the exception without throwing when data is absent.
🧹 Nitpick comments (1)
backend/src/modules/auth/jwt/jwt.guard.spec.ts (1)
10-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd test coverage for the
errorrethrow/wrap branches.Tests cover the
info-based mapping (TOKEN_EXPIRED/INVALID_TOKEN/UNAUTHORIZED) and the success path, but nothandleRequest's handling of a truthyerrorargument (rethrow ifError, wrap otherwise) — the two branches that determine whether an auth failure surfaces as a raw 500 vs. a structured 401.✅ Suggested additional tests
+ it('Error 인스턴스인 error는 그대로 다시 던진다', () => { + const original = new Error('strategy failure'); + expect(() => guard.handleRequest(original, false, undefined)).toThrow(original); + }); + + it('Error가 아닌 error는 래핑하여 던진다', () => { + expect(() => guard.handleRequest('boom', false, undefined)).toThrow( + 'Authentication failed', + ); + });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@backend/src/modules/auth/jwt/jwt.guard.spec.ts` around lines 10 - 77, Add tests for the truthy error branches in JwtAuthGuard.handleRequest: verify an Error instance is rethrown unchanged, and verify a non-Error truthy value is wrapped as the structured unauthorized HttpException response. Reuse getResponse where appropriate and assert the resulting status and response shape.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@frontend/src/store/useSocketStore.ts`:
- Around line 104-125: Update the unexpected-error reporting block in the socket
exception handler to safely handle missing or malformed data, avoiding the
direct data.code dereference used by Sentry.captureMessage. Preserve
classification via getSocketErrorAction(data?.code) and ensure the report/log
path still records the exception without throwing when data is absent.
---
Nitpick comments:
In `@backend/src/modules/auth/jwt/jwt.guard.spec.ts`:
- Around line 10-77: Add tests for the truthy error branches in
JwtAuthGuard.handleRequest: verify an Error instance is rethrown unchanged, and
verify a non-Error truthy value is wrapped as the structured unauthorized
HttpException response. Reuse getResponse where appropriate and assert the
resulting status and response shape.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: c99be240-f2d8-4bf1-a794-729bcdd65487
📒 Files selected for processing (28)
backend/src/common/exception_filters/AllHttpExceptionFilter.spec.tsbackend/src/common/exception_filters/AllHttpExceptionFilter.tsbackend/src/common/exception_filters/AllWsExceptionFilter.spec.tsbackend/src/common/exception_filters/AllWsExceptionFilter.tsbackend/src/common/exceptions/auth-unauthorized.exception.spec.tsbackend/src/common/exceptions/auth-unauthorized.exception.tsbackend/src/modules/auth/auth.controller.tsbackend/src/modules/auth/jwt/jwt.guard.spec.tsbackend/src/modules/auth/jwt/jwt.guard.tsfrontend/package.jsonfrontend/src/app/(post)/group/[groupId]/post/[draftId]/page.tsxfrontend/src/app/(post)/group/_components/GroupAccessGuard.tsxfrontend/src/app/(post)/group/_components/GroupDraftFloating.tsxfrontend/src/app/providers.tsxfrontend/src/hooks/useApi.tsfrontend/src/lib/types/recordCollaboration.tsfrontend/src/lib/types/response.tsfrontend/src/lib/utils/error/publishHandler.tsfrontend/src/lib/utils/errorHandler.test.tsfrontend/src/lib/utils/errorHandler.tsfrontend/src/lib/utils/errorReporter.test.tsfrontend/src/lib/utils/errorReporter.tsfrontend/src/lib/utils/errorToast.test.tsfrontend/src/lib/utils/errorToast.tsfrontend/src/lib/utils/socketErrorPolicy.test.tsfrontend/src/lib/utils/socketErrorPolicy.tsfrontend/src/store/useSocketStore.tsfrontend/vitest.config.ts
요약 (연관 이슈 번호 포함)
code + safeMessage기반으로 표준화했습니다.작업 내용 + 스크린샷
백엔드
details, stack, 내부 예외 원문 제거requestId추가code,message,requestId응답 표준화표준 에러 응답 예시:
{ "success": false, "data": null, "error": { "code": "INTERNAL_SERVER_ERROR", "message": "일시적인 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.", "requestId": "req_123456" } }프론트엔드
error.code기반 사용자 메시지 매핑 추가ApiError에requestId전달error.message기반 토스트 및 조건 분기 제거requestId,errorCode, 발생 위치 태그 추가실제 걸린 시간
작업하며 고민했던 점(선택)
테스트 실행 여부
리뷰 참고사항(선택)
requestId는 현재 예외 필터에서 생성되며 요청 전체 로그 컨텍스트로 전파되지는 않습니다.시각 자료(이미지/영상, 있다면)(선택)
Summary by CodeRabbit
Bug Fixes
Tests