Documentation
Errors

Errors

Whenever an error occurs in a process, SecrecyClient throws an "error". This error contains all the information that you need to handle the error in the client. The SecrecyClient defines a list of error codes that each represent a different type of error.

Error codes

A SecrecyError is a plain object, not an instance of Error. It is discriminated by its name: a ClientError is raised by the library itself, a ServerError is forwarded from the Secrecy API.

errors.ts
// Thrown by the library itself
type ClientError = {
  name: 'ClientError';
  code: 'NOT_FOUND';
  message: string;
};
 
// Forwarded from the Secrecy API
type ServerError = {
  name: 'TRPCError';
  code:
    | 'PARSE_ERROR'
    | 'BAD_REQUEST'
    | 'INTERNAL_SERVER_ERROR'
    | 'NOT_IMPLEMENTED'
    | 'UNAUTHORIZED'
    | 'FORBIDDEN'
    | 'NOT_FOUND'
    | 'METHOD_NOT_SUPPORTED'
    | 'TIMEOUT'
    | 'CONFLICT'
    | 'PRECONDITION_FAILED'
    | 'PAYLOAD_TOO_LARGE'
    | 'UNPROCESSABLE_CONTENT'
    | 'TOO_MANY_REQUESTS'
    | 'CLIENT_CLOSED_REQUEST';
  message: string;
  data?: unknown;
};
 
type SecrecyError = ClientError | ServerError;

Error Handling

As you can see in our example, if an error occurs during the call, the function checks if the error is a SecrecyError by using the helper function isSecrecyError. If so, you can access the code, message and name properties of the error, which can help in debugging issues related to the API call. The name property narrows the error down to one of the two kinds. The dedicated isClientError and isServerError guards are not on the package root: import them from @secrecy/lib/error/client and @secrecy/lib/error/server.

errors.ts
import { isSecrecyError } from '@secrecy/lib';
 
const handlingSecrecyError = async (): Promise<SelfUser | undefined> => {
  if (!secrecyClient) {
    throw 'No client';
  }
 
  try {
    // whatever the Secrecy methods
    const user = await secrecyClient.me();
    return user;
  } catch (e) {
    // Check if the error is a SecrecyError
    if (isSecrecyError(e)) {
      const { message, code, name } = e;
      console.error({ message, code, name });
    }
 
    // Narrow it down further when needed
    if (
      isSecrecyError(e) &&
      e.name === 'TRPCError' &&
      e.code === 'UNAUTHORIZED'
    ) {
      // the session is no longer valid
    }
  }
};