Skip to main content

Error

Throw a GrpcError from a service, guard, middleware, interceptor, or pipe to finish the call with a gRPC status. The adapter sends the error's code, details, and optional metadata. This works for unary and streaming RPCs.

class GrpcError extends Error {
constructor(
code: Exclude<GrpcStatusCode, GrpcStatusCode.OK>,
details: string,
errorOptions?: ErrorOptions,
metadata?: GrpcMetadata,
)
}

metadata is a record of string or Buffer values. @grpc/grpc-js accepts lowercase keys.

import { NotFoundGrpcError, RPC, Service } from '@inversifyjs/grpc-core';

import {
type HeroRequest,
type HeroResponse,
heroServiceDefinition,
} from './loadHeroServiceDefinition.js';

@Service(heroServiceDefinition)
export class NotFoundHeroService {
@RPC('GetHero')
public getHero(call: { request: HeroRequest }): HeroResponse {
if (call.request.id === 'missing') {
throw new NotFoundGrpcError(`Hero ${call.request.id} was not found`);
}

return {
name: call.request.id,
};
}
}

A thrown Error that is not a GrpcError, and that no error filter handles, becomes status UNKNOWN with details Unknown. The original error is logged when logging is enabled.

Status classes​

Each subclass sets one GrpcStatusCode and a default details string. Pass your own details, ErrorOptions, and metadata to the constructor when you need them.

ClassStatusDefault details
CancelledGrpcErrorCANCELLEDCancelled
UnknownGrpcErrorUNKNOWNUnknown
InvalidArgumentGrpcErrorINVALID_ARGUMENTInvalid Argument
DeadlineExceededGrpcErrorDEADLINE_EXCEEDEDDeadline Exceeded
NotFoundGrpcErrorNOT_FOUNDNot Found
AlreadyExistsGrpcErrorALREADY_EXISTSAlready Exists
PermissionDeniedGrpcErrorPERMISSION_DENIEDPermission Denied
ResourceExhaustedGrpcErrorRESOURCE_EXHAUSTEDResource Exhausted
FailedPreconditionGrpcErrorFAILED_PRECONDITIONFailed Precondition
AbortedGrpcErrorABORTEDAborted
OutOfRangeGrpcErrorOUT_OF_RANGEOut Of Range
UnimplementedGrpcErrorUNIMPLEMENTEDUnimplemented
InternalGrpcErrorINTERNALInternal
UnavailableGrpcErrorUNAVAILABLEUnavailable
DataLossGrpcErrorDATA_LOSSData Loss
UnauthenticatedGrpcErrorUNAUTHENTICATEDUnauthenticated

Import them from @inversifyjs/grpc-core.