본문 바로가기
버전: 9.x

오류 처리

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

프로시저에서 오류가 발생하면 tRPC는 "error" 속성을 포함하는 객체로 클라이언트에 응답합니다. 이 속성에는 클라이언트에서 오류를 처리하는 데 필요한 모든 정보가 포함됩니다.

잘못된 요청 입력으로 인한 오류 응답 예시:

json
{
"id": null,
"error": {
"message": "\"password\" must be at least 4 characters",
"code": -32600,
"data": {
"code": "BAD_REQUEST",
"httpStatus": 400,
"stack": "...",
"path": "user.changepassword"
}
}
}
json
{
"id": null,
"error": {
"message": "\"password\" must be at least 4 characters",
"code": -32600,
"data": {
"code": "BAD_REQUEST",
"httpStatus": 400,
"stack": "...",
"path": "user.changepassword"
}
}
}

오류 코드

tRPC는 각기 다른 유형의 오류를 나타내며 서로 다른 HTTP 코드로 응답하는 오류 코드 목록을 정의합니다.

CodeDescriptionHTTP code
BAD_REQUESTThe server cannot or will not process the request due to something that is perceived to be a client error.400
UNAUTHORIZEDThe client request has not been completed because it lacks valid authentication credentials for the requested resource.401
FORBIDDENThe server was unauthorized to access a required data source, such as a REST API.403
NOT_FOUNDThe server cannot find the requested resource.404
TIMEOUTThe server would like to shut down this unused connection.408
CONFLICTThe server request resource conflict with the current state of the target resource.409
PRECONDITION_FAILEDAccess to the target resource has been denied.412
PAYLOAD_TOO_LARGERequest entity is larger than limits defined by server.413
METHOD_NOT_SUPPORTEDThe server knows the request method, but the target resource doesn't support this method.405
CLIENT_CLOSED_REQUESTAccess to the resource has been denied.499
INTERNAL_SERVER_ERRORAn unspecified error occurred.500

오류 던지기

tRPC는 프로시저 내부에서 발생한 오류를 표현하는 데 사용할 수 있는 오류 서브클래스 TRPCError를 제공합니다.

예를 들어, 다음과 같은 오류를 던지는 경우:

server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router().query('hello', {
resolve: () => {
throw new trpc.TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected error occurred, please try again later.',
// optional: pass the original error to retain stack trace
cause: theError,
});
},
});
// [...]
server.ts
ts
import * as trpc from '@trpc/server';
const appRouter = trpc.router().query('hello', {
resolve: () => {
throw new trpc.TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected error occurred, please try again later.',
// optional: pass the original error to retain stack trace
cause: theError,
});
},
});
// [...]

다음과 같은 응답이 발생합니다:

json
{
"id": null,
"error": {
"message": "An unexpected error occurred, please try again later.",
"code": -32603,
"data": {
"code": "INTERNAL_SERVER_ERROR",
"httpStatus": 500,
"stack": "...",
"path": "hello"
}
}
}
json
{
"id": null,
"error": {
"message": "An unexpected error occurred, please try again later.",
"code": -32603,
"data": {
"code": "INTERNAL_SERVER_ERROR",
"httpStatus": 500,
"stack": "...",
"path": "hello"
}
}
}

오류 처리

프로시저에서 발생하는 모든 오류는 클라이언트로 전송되기 전에 onError 메서드를 거칩니다. 여기서 오류를 처리하거나 수정할 수 있습니다.

pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// ...
onError({ error, type, path, input, ctx, req }) {
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
},
});
pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// ...
onError({ error, type, path, input, ctx, req }) {
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
},
});

onError 매개변수는 오류 및 오류가 발생한 컨텍스트에 관한 모든 정보를 포함하는 객체입니다:

ts
{
error: TRPCError; // the original error
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined; // path of the procedure that was triggered
input: unknown;
ctx: Context | undefined;
req: BaseRequest; // request object
}
ts
{
error: TRPCError; // the original error
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined; // path of the procedure that was triggered
input: unknown;
ctx: Context | undefined;
req: BaseRequest; // request object
}