T-Invest Node SDK Node.js
On this page

Handle errors

When an SDK call fails, check for SdkError and inspect code and source. Handle known causes and propagate unexpected errors. Base decisions about retries, cancellation, and diagnosis on these stable fields.

Identify the cause by code and source

A single code can have several causes. For example, CANCELLED can come from a local AbortSignal or the provider. Check code together with source when the distinction matters to the application.

The following snippets assume that sdk is already initialized. See Your first SDK call to set it up and close it. Each example handles one case and propagates other errors to the caller.

errors-and-lifecycle.ts
import { isSdkError, SdkErrorCode } from '@woodger/t-invest-node-sdk';

Handle a TLS error

When sdk.users.getAccounts() fails, check for both SdkErrorCode.Unavailable and source: 'tls'. This combination identifies a certificate-chain or server-name verification failure. The example prompts you to check the API address and CA settings.

errors-and-lifecycle.ts
try {
  await sdk.users.getAccounts({});
}
catch (error) {
  if (
    isSdkError(error, SdkErrorCode.Unavailable)
    && error.source === 'tls'
  ) {
    console.error('Проверьте адрес API и настройки CA-сертификата');
  }
  else {
    throw error;
  }
}

Handle an expired deadline

Pass AbortSignal.timeout(5_000) to limit the wait to five seconds. The example recognizes an expired deadline when the signal has aborted and the error has SdkErrorCode.Cancelled with source: 'abort'.

errors-and-lifecycle.ts
const deadline = AbortSignal.timeout(5_000);

try {
  await sdk.users.getAccounts({}, { signal: deadline });
}
catch (error) {
  if (
    deadline.aborted
    && isSdkError(error, SdkErrorCode.Cancelled)
    && error.source === 'abort'
  ) {
    console.error('Истёк срок ожидания запроса');
  }
  else {
    throw error;
  }
}

Handle an authorization error

An error with SdkErrorCode.Unauthenticated and source: 'grpc' indicates that the provider rejected authentication. The example logs error.path to identify the call that failed.

errors-and-lifecycle.ts
try {
  await sdk.users.getAccounts({});
}
catch (error) {
  if (
    isSdkError(error, SdkErrorCode.Unauthenticated)
    && error.source === 'grpc'
  ) {
    console.error('Провайдер отклонил токен', { path: error.path });
  }
  else {
    throw error;
  }
}

Distinguish message size limits from provider quotas

ResourceExhausted can indicate different limits. The snippet diagnoses the error and then propagates it. The application controls retries.

errors-and-lifecycle.ts
try {
  await sdk.users.getAccounts({});
}
catch (error) {
  if (!isSdkError(error, SdkErrorCode.ResourceExhausted)) {
    throw error;
  }

  if (error.source === 'sdk') {
    console.error('Ответ превысил локальный лимит gRPC-сообщения', {
      path: error.path
    });
  }
  else if (error.source === 'grpc') {
    console.error('Исчерпана квота провайдера', {
      path: error.path,
      details: error.details
    });
  }

  throw error;
}

Use error codes

The SDK maps gRPC statuses to stable SdkErrorCode names.

For an error with source: 'grpc', code holds the symbolic name of a standard gRPC status other than OK.

errors-and-lifecycle.ts
SdkErrorCode.InvalidArgument;
SdkErrorCode.NotFound;
SdkErrorCode.Unauthenticated;
SdkErrorCode.ResourceExhausted;

This snippet shows the values INVALID_ARGUMENT, NOT_FOUND, UNAUTHENTICATED, and RESOURCE_EXHAUSTED.

The exported SdkErrorCode enum lists the error codes and excludes OK. SdkErrorCode.SdkClosed and SdkErrorCode.UnknownUnaryLimit are SDK-specific codes. Combine code and source whenever you need to determine the origin of an error.

Identify the error source

SdkErrorCode.InvalidArgument has source: 'grpc' when provider validation fails and source: 'sdk' for a local configuration error. Check source along with code to identify where the error originated.

source Meaning
grpc Transport or provider error
tls Certificate chain or server name verification failed
abort Application canceled the call through AbortSignal
lifecycle SDK already closed
sdk SDK rejected local configuration, a request, or runtime state

A runtime error can come from outside SdkError. Call isSdkError() first and keep or propagate unknown errors without forcing a cast. For example, synchronous exceptions from an application's onHeader or onTrailer handler propagate unchanged, without an SdkError wrapper.

The SDK reports unambiguous certificate chain and server name verification errors as SdkErrorCode.Unavailable with source: 'tls'. A regular UNAVAILABLE from the provider or network, including DNS failures, refused or reset connections, and timeouts, keeps source: 'grpc'. Use source to identify TLS failures and skip ordinary availability retries. The path, details, and cause fields are available for diagnosis.

An inbound gRPC message above the SDK's internal limit produces SdkErrorCode.ResourceExhausted with source: 'sdk'. Exhausted provider quota returns the same code with source: 'grpc'. The SDK retains path, details, and cause in both cases. Use source to distinguish the causes.

Local request serialization and response parsing errors have SdkErrorCode.Internal with source: 'sdk'. INTERNAL from the provider keeps source: 'grpc'. The SDK retains path, details, and cause for diagnosis. Classify the error using source.

Use diagnostic fields

  • path contains the gRPC method path when known.
  • details contains diagnostic text from the transport or provider. Treat the text as diagnostic output and avoid parsing it with a regular expression to infer a business error code.
  • cause retains the original error for diagnosis. Keep business logic independent of the nice-grpc error class.

isSdkError() recognizes a compatible SdkError from another physical copy of the package in the same JavaScript realm. After transfer through JSON, IPC, or worker serialization, use an application protocol to identify the error.

Close the SDK

sdk.close() can be called repeatedly. The first call has three effects.

  • Prevents new service clients from being created and existing clients from making calls.
  • Cancels operations still waiting for local unary quota.
  • Closes the shared channel.

For operations already passed to the transport, abort them using your AbortSignal and wait for completion before calling sdk.close(). See Streams and cancellation for the streaming shutdown sequence.

Decide whether to retry

Treat the gRPC status as one input to the retry decision. Check the following before retrying.

  • Whether the operation is idempotent.
  • Whether the provider may have already performed the change.
  • Whether retry or rate-limit metadata is available.
  • What delay between attempts and overall time limit the application can accept.

This is especially important for ResourceExhausted, Unavailable, DeadlineExceeded, and RPCs that change data. A generic SDK retry interceptor would miss these distinctions.

For ResourceExhausted, first check source. A value of sdk means the inbound message exceeded the SDK transport limit and will hit the same limit on retry. A value of grpc indicates a provider response. Check the metadata, idempotency, and retry delay before repeating the call.