npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@plyaz/errors

v1.5.0

Published

Comprehensive error handling system for Plyaz ecosystem with standardized error classes, validation, input sanitization & security. Supports frontend, backend & blockchain integration.

Downloads

1,328

Readme

@plyaz/errors

Comprehensive error handling system for the Plyaz ecosystem with standardized error classes, validation, input sanitization & security support for frontend, backend & blockchain integration.

Installation

pnpm add @plyaz/errors

Quick Start

Basic Error Usage

import { ValidationError, ApiError, AuthError } from '@plyaz/errors';

// Throw a validation error
throw new ValidationError('VALIDATION_ERROR', 'en', {
  field: 'email',
  message: 'Invalid email format'
});

// Throw an API error
throw new ApiError('NOT_FOUND', 404, {
  entity: 'User',
  id: '123'
});

// Throw an authentication error
throw new AuthError('AUTH_TOKEN_EXPIRED');

Frontend Error Handling

import { useErrorHandler, ErrorBoundary } from '@plyaz/errors/frontend';

function MyComponent() {
  const { handleError, isAuthError } = useErrorHandler();
  
  const fetchData = async () => {
    try {
      // API call
    } catch (error) {
      handleError(error, {
        notFound: () => navigate('/404'),
        unauthorized: () => navigate('/login'),
        default: (err) => console.error(err)
      });
    }
  };
  
  return (
    <ErrorBoundary fallback={<ErrorPage />}>
      {/* Your component */}
    </ErrorBoundary>
  );
}

Backend Error Handling (NestJS)

import { GlobalErrorFilter } from '@plyaz/errors/backend';

// In main.ts
app.useGlobalFilters(new GlobalErrorFilter());

// In a service
import { NotFoundError, ConflictError } from '@plyaz/errors';

async findUser(id: string) {
  const user = await this.prisma.user.findUnique({ where: { id } });
  
  if (!user) {
    throw new NotFoundError('User not found', { userId: id });
  }
  
  return user;
}

Error exceptions

Base Error Hierarchy

BaseError
├── ValidationError     - Input validation failures
├── AuthError          - Authentication/authorization errors
│   ├── UnauthorizedError
│   └── ForbiddenError
├── ApiError           - API-related errors
│   ├── NotFoundError
│   ├── ConflictError
│   └── TimeoutError
├── BusinessError      - Business logic errors
└── BlockchainError    - Blockchain-specific errors
    ├── TransactionError
    ├── WalletError
    └── ContractError

Error Properties

All errors include:

  • name - Error class name
  • message - Human-readable message (i18n supported)
  • code - Application error code (e.g., "AUTH_TOKEN_EXPIRED")
  • statusCode - HTTP status code
  • timestamp - ISO timestamp of occurrence
  • details - Additional context data
  • cause - Original error if wrapping
  • correlationId - Request tracking ID
  • stack - Stack trace (dev only)

Creating Custom Errors

import { BusinessError } from '@plyaz/errors';

export class InsufficientFundsError extends BusinessError {
  constructor(details?: any) {
    super('INSUFFICIENT_FUNDS', 'en', details);
    this.statusCode = 402;
  }
}

// Usage
throw new InsufficientFundsError({
  available: 100,
  required: 150,
  currency: 'USD'
});

Input Sanitization

Protect against XSS and SQL injection:

import { sanitizeHtml, sanitizeSql } from '@plyaz/errors/sanitizers';

// Sanitize HTML input
const safeHtml = sanitizeHtml(userInput, {
  allowedTags: ['b', 'i', 'em', 'strong'],
  allowedAttributes: {}
});

// Sanitize SQL input
const safeSqlInput = sanitizeSql(userQuery);

Error Serialization

Transport errors between services:

import { serializeError, deserializeError } from '@plyaz/errors/serializers';

// Convert error to plain object
const serialized = serializeError(error);

// Send over network...

// Recreate error instance
const error = deserializeError(serialized);

Logger Integration

Works seamlessly with @plyaz/logger:

import { logError } from '@plyaz/errors/utils';
import { logger } from '@plyaz/logger';

try {
  // Some operation
} catch (error) {
  logError(logger, error, {
    userId: user.id,
    context: 'user-creation',
    correlationId: request.id
  });
}

Standard Error Response Format

All errors follow this structure:

interface ErrorResponse {
  statusCode: number;      // HTTP status code
  errorCode: string;       // Application error code
  message: string;         // Human-readable message
  errors?: ErrorDetail[];  // Detailed validation errors
  correlationId?: string;  // Request tracing ID
  timestamp: string;       // ISO timestamp
}

interface ErrorDetail {
  field?: string;          // Field with error
  message: string;         // Error message
  errorCode: string;       // Specific error code
  context?: any;           // Additional context
}

Common Error Codes

Authentication Errors

  • AUTH_INVALID_CREDENTIALS - Invalid login credentials
  • AUTH_TOKEN_EXPIRED - Authentication token expired
  • AUTH_TOKEN_INVALID - Invalid authentication token
  • AUTH_INSUFFICIENT_PERMISSIONS - Lacks required permissions

Validation Errors

  • VALIDATION_ERROR - General validation failure
  • REQUIRED_FIELD_MISSING - Required field not provided
  • INVALID_FORMAT - Field format invalid
  • STRING_TOO_SHORT - String below minimum length
  • STRING_TOO_LONG - String exceeds maximum length

Database Errors

  • DB_ENTITY_NOT_FOUND - Entity not found
  • DB_DUPLICATE_ENTRY - Unique constraint violation
  • DB_TRANSACTION_FAILED - Transaction failure

Blockchain Errors

  • BLOCKCHAIN_CONNECTION_ERROR - Blockchain connection failed
  • TRANSACTION_FAILED - Transaction failed
  • INSUFFICIENT_FUNDS - Insufficient funds

Development Commands

# Development
pnpm dev              # Start development with watch mode
pnpm build            # Build for production
pnpm clean            # Clean dist directory

# Testing
pnpm test             # Run tests once
pnpm test:watch       # Run tests in watch mode
pnpm test:coverage    # Run tests with coverage
pnpm test:ui          # Open Vitest UI

# Code Quality
pnpm lint             # Run ESLint
pnpm lint:fix         # Auto-fix linting issues
pnpm format           # Format code with Prettier
pnpm type:check       # TypeScript type checking

# Security
pnpm security:check   # Security audit
pnpm audit:fix        # Auto-fix vulnerabilities

Package Dependencies

Per Plyaz monorepo architecture:

Can Import From

  • @plyaz/types - Error type definitions
  • @plyaz/utils - Utility functions
  • @plyaz/config - Configuration constants
  • @plyaz/translations - i18n error messages
  • @plyaz/logger - Error logging integration

Cannot Import From

  • @plyaz/api, @plyaz/web3, @plyaz/ui, @plyaz/hooks, @plyaz/store

Contributing

When adding new error types:

  1. Extend from appropriate base class
  2. Add error code to constants
  3. Add translations to @plyaz/translations
  4. Update type definitions in @plyaz/types
  5. Add unit tests with 90% coverage minimum
  6. Document in README with examples

License

ISC