Skip to content

Add community plugin: Elysia HTTP Exception #598

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 11, 2025
Merged

Conversation

codev911
Copy link
Contributor

@codev911 codev911 commented Aug 11, 2025

🚨 Add Elysia HTTP Exception Plugin

Summary

This PR introduces a comprehensive HTTP exception handling plugin for Elysia, inspired by NestJS's HTTP Exception system. The plugin provides structured exception classes for all standard 4xx and 5xx HTTP status codes with type-safe error handling.

Motivation

While building applications with Elysia, I found myself repeatedly creating custom error handling patterns for different HTTP status codes. This led to inconsistent error responses and boilerplate code across projects.

Drawing inspiration from NestJS's elegant HTTP Exception system, I created this plugin to bring the same level of structure and consistency to Elysia applications.

What This Plugin Provides

✨ Features

  • Complete HTTP Status Coverage: Support for all standard 4xx and 5xx HTTP status codes
  • Type-Safe: Full TypeScript support with proper type definitions
  • Flexible Error Data: Accept string messages, objects, or Error instances
  • Two Usage Patterns: Use either throw statements or the httpException decorator
  • Automatic Error Handling: Built-in handler for common Elysia errors (PARSE, VALIDATION, NOT_FOUND, etc.)
  • Zero Configuration: Works out of the box with sensible defaults

🎯 Available Exception Classes

4xx Client Errors:

  • BadRequestException (400)
  • UnauthorizedException (401)
  • ForbiddenException (403)
  • NotFoundException (404)
  • MethodNotAllowedException (405)
  • ConflictException (409)
  • UnprocessableEntityException (422)
  • TooManyRequestsException (429)
  • And 20+ more...

5xx Server Errors:

  • InternalServerErrorException (500)
  • NotImplementedException (501)
  • BadGatewayException (502)
  • ServiceUnavailableException (503)
  • GatewayTimeoutException (504)
  • And more...

Basic Usage Example

import { Elysia } from 'elysia';
import { httpExceptionPlugin, NotFoundException, BadRequestException } from 'elysia-http-exception';

const app = new Elysia()
  .use(httpExceptionPlugin())
  .get('/users/:id', ({ params }) => {
    const userId = parseInt(params.id);
    
    if (isNaN(userId)) {
      throw new BadRequestException('User ID must be a valid number');
    }
    
    if (userId === 404) {
      throw new NotFoundException(`User with ID ${userId} not found`);
    }
    
    return { id: userId, name: `User ${userId}` };
  })
  .listen(3000);

Response Examples

Simple string message:

curl http://localhost:3000/users/invalid
{
  "statusCode": 400,
  "message": "User ID must be a valid number"
}

Custom object data:

throw new UnprocessableEntityException({
  error: 'VALIDATION_FAILED',
  details: {
    field: 'email',
    message: 'Invalid email format'
  },
  timestamp: new Date().toISOString()
});
{
  "error": "VALIDATION_FAILED",
  "details": {
    "field": "email", 
    "message": "Invalid email format"
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}

Alternative Usage: Decorator Pattern

app.get('/users/:id', ({ params, httpException }) => {
  const userId = parseInt(params.id);
  
  if (isNaN(userId)) {
    return httpException(new BadRequestException('User ID must be a valid number'));
  }
  
  if (userId === 404) {
    return httpException(new NotFoundException(`User with ID ${userId} not found`));
  }
  
  return { id: userId, name: `User ${userId}` };
});

Advanced Examples

Authentication & Authorization

app.get('/profile', ({ headers }) => {
  const authHeader = headers['authorization'];
  
  if (!authHeader) {
    throw new UnauthorizedException({
      error: 'MISSING_AUTH_HEADER',
      message: 'Authorization header is required',
      requiredFormat: 'Bearer <token>'
    });
  }
  
  if (!authHeader.startsWith('Bearer ')) {
    throw new UnauthorizedException('Invalid authorization format');
  }
  
  return { user: { id: 1, name: 'John Doe' } };
});

Rate Limiting

app.get('/api/data', () => {
  const rateLimitExceeded = checkRateLimit(); // Your logic
  
  if (rateLimitExceeded) {
    throw new TooManyRequestsException({
      message: 'Rate limit exceeded',
      retryAfter: 60,
      limit: 100,
      remaining: 0
    });
  }
  
  return { data: 'Your API data' };
});

File Upload Validation

app.post('/upload', ({ request }) => {
  const contentLength = parseInt(request.headers.get('content-length') || '0');
  const maxSize = 5 * 1024 * 1024; // 5MB
  
  if (contentLength > maxSize) {
    throw new PayloadTooLargeException({
      error: 'FILE_TOO_LARGE',
      message: 'File size exceeds maximum allowed size',
      maxSize: `${maxSize / 1024 / 1024}MB`,
      receivedSize: `${(contentLength / 1024 / 1024).toFixed(2)}MB`
    });
  }
  
  return { message: 'Upload successful' };
});

Built-in Error Handling

The plugin automatically handles common Elysia errors:

  • PARSE: JSON parsing errors → 400 Bad Request
  • VALIDATION: Schema validation errors → 400 Bad Request
  • NOT_FOUND: Route not found → 404 Not Found
  • INVALID_COOKIE_SIGNATURE: Invalid cookies → 400 Bad Request
  • INVALID_FILE_TYPE: Unsupported file types → 415 Unsupported Media Type

Inspiration from NestJS

This plugin draws heavy inspiration from NestJS's HTTP Exception system, specifically:

NestJS References:

Package Information

Installation

# Using bun (recommended)
bun add elysia-http-exception

# Using npm
npm install elysia-http-exception

Testing & Quality

  • ✅ Comprehensive test coverage (198 unit tests)
  • ✅ E2E tests with example applications
  • ✅ TypeScript strict mode compliance
  • ✅ Full documentation with examples
  • ✅ Automated CI/CD pipeline

Why This Should Be Added

  1. Consistency: Provides a standardized way to handle HTTP exceptions across Elysia applications
  2. Developer Experience: Reduces boilerplate and improves error handling patterns
  3. Type Safety: Full TypeScript support with intellisense
  4. Community Value: Fills a common need in the Elysia ecosystem
  5. Proven Pattern: Based on successful patterns from established frameworks like NestJS
  6. Zero Breaking Changes: Completely additive, doesn't affect existing code

Community Impact

This plugin addresses a common pattern that many Elysia developers implement manually. By providing a standardized, well-tested solution, it can:

  • Reduce development time for new projects
  • Improve consistency across the Elysia ecosystem
  • Lower the learning curve for developers coming from other frameworks
  • Serve as a reference implementation for plugin development

I believe this plugin would be a valuable addition to the official Elysia plugin ecosystem. It's production-ready, well-documented, and solves a real problem that many developers face when building APIs with Elysia.

Thank you for considering this contribution to the Elysia community! 🚀

Summary by CodeRabbit

  • Documentation
    • Added a new Community plugin entry: “Elysia HTTP Exception,” including a link and brief description to aid discovery and adoption.
    • Improves the completeness and visibility of error-handling plugins within the catalog for users evaluating options.
    • No changes to page structure, functionality, or existing content.
    • No API or behavior changes; no user action required.

Copy link

coderabbitai bot commented Aug 11, 2025

Walkthrough

Adds a new community plugin entry, “Elysia HTTP Exception,” with a link and description to docs/plugins/overview.md. No other changes.

Changes

Cohort / File(s) Summary
Docs — Plugins overview
docs/plugins/overview.md
Added a new Community plugins entry: “Elysia HTTP Exception” with link and description; no structural changes.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Poem

I twitch my whiskers, tap my paw,
A plugin hops into the docs—ooh, la!
Elysia’s errors, neatly penned,
A gentle link, a tidy friend.
Thump of approval—onward, awe! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b219a3 and 02f4b4e.

📒 Files selected for processing (1)
  • docs/plugins/overview.md (1 hunks)
🔇 Additional comments (2)
docs/plugins/overview.md (2)

56-56: LGTM: solid addition to Community plugins.

Entry looks consistent in naming and link style with surrounding items.


56-56: Refine plugin description to highlight TypeScript-first design, decorator support, and automatic handling

Verified that the GitHub repo (200 OK) and npm package (v0.1.3) exist, and README confirms full TypeScript support, decorator usage, and automatic error handling. Apply this change:

• docs/plugins/overview.md (line 56)

-   [Elysia HTTP Exception](https://github.com/codev911/elysia-http-exception) - Elysia plugin for HTTP 4xx/5xx error handling with structured exception classes
+   [Elysia HTTP Exception](https://github.com/codev911/elysia-http-exception) - TypeScript-first HTTP exception system with structured 4xx/5xx exception classes, decorator support, and automatic handling of common Elysia errors
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@fecony fecony merged commit 5628141 into elysiajs:main Aug 11, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants