|
| 1 | +import { Elysia } from 'elysia'; |
| 2 | +import { |
| 3 | + httpExceptionPlugin, |
| 4 | + // 4xx Client Error Exceptions |
| 5 | + BadRequestException, |
| 6 | + UnauthorizedException, |
| 7 | + PaymentRequiredException, |
| 8 | + ForbiddenException, |
| 9 | + NotFoundException, |
| 10 | + MethodNotAllowedException, |
| 11 | + NotAcceptableException, |
| 12 | + RequestTimeoutException, |
| 13 | + ConflictException, |
| 14 | + GoneException, |
| 15 | + LengthRequiredException, |
| 16 | + PreconditionFailedException, |
| 17 | + PayloadTooLargeException, |
| 18 | + UriTooLongException, |
| 19 | + UnsupportedMediaTypeException, |
| 20 | + RangeNotSatisfiableException, |
| 21 | + ExpectationFailedException, |
| 22 | + ImATeapotException, |
| 23 | + MisdirectedRequestException, |
| 24 | + UnprocessableEntityException, |
| 25 | + LockedException, |
| 26 | + FailedDependencyException, |
| 27 | + TooEarlyException, |
| 28 | + UpgradeRequiredException, |
| 29 | + PreconditionRequiredException, |
| 30 | + TooManyRequestsException, |
| 31 | + RequestHeaderFieldsTooLargeException, |
| 32 | + UnavailableForLegalReasonsException, |
| 33 | + // 5xx Server Error Exceptions |
| 34 | + InternalServerErrorException, |
| 35 | + NotImplementedException, |
| 36 | + BadGatewayException, |
| 37 | + ServiceUnavailableException, |
| 38 | + GatewayTimeoutException, |
| 39 | + HttpVersionNotSupportedException, |
| 40 | + VariantAlsoNegotiatesException, |
| 41 | + InsufficientStorageException, |
| 42 | + LoopDetectedException, |
| 43 | + NotExtendedException, |
| 44 | + NetworkAuthenticationRequiredException, |
| 45 | +} from 'elysia-http-exception'; |
| 46 | + |
| 47 | +const app = new Elysia() |
| 48 | + .use(httpExceptionPlugin()) |
| 49 | + .get('/', () => 'Elysia HTTP Exception Examples - Try different endpoints to see various errors!') |
| 50 | + |
| 51 | + // 4xx Client Errors |
| 52 | + .get('/400', () => { |
| 53 | + throw new BadRequestException('Invalid request format'); |
| 54 | + }) |
| 55 | + .get('/401', () => { |
| 56 | + throw new UnauthorizedException('Authentication required'); |
| 57 | + }) |
| 58 | + .get('/402', () => { |
| 59 | + throw new PaymentRequiredException('Payment is required to access this resource'); |
| 60 | + }) |
| 61 | + .get('/403', () => { |
| 62 | + throw new ForbiddenException('You do not have permission to access this resource'); |
| 63 | + }) |
| 64 | + .get('/404', () => { |
| 65 | + throw new NotFoundException('The requested resource was not found'); |
| 66 | + }) |
| 67 | + .get('/405', () => { |
| 68 | + throw new MethodNotAllowedException('This HTTP method is not allowed for this endpoint'); |
| 69 | + }) |
| 70 | + .get('/406', () => { |
| 71 | + throw new NotAcceptableException('The requested format is not acceptable'); |
| 72 | + }) |
| 73 | + .get('/408', () => { |
| 74 | + throw new RequestTimeoutException('Request timeout occurred'); |
| 75 | + }) |
| 76 | + .get('/409', () => { |
| 77 | + throw new ConflictException('Resource conflict detected'); |
| 78 | + }) |
| 79 | + .get('/410', () => { |
| 80 | + throw new GoneException('This resource is no longer available'); |
| 81 | + }) |
| 82 | + .get('/411', () => { |
| 83 | + throw new LengthRequiredException('Content-Length header is required'); |
| 84 | + }) |
| 85 | + .get('/412', () => { |
| 86 | + throw new PreconditionFailedException('Precondition in request headers failed'); |
| 87 | + }) |
| 88 | + .get('/413', () => { |
| 89 | + throw new PayloadTooLargeException('Request payload is too large'); |
| 90 | + }) |
| 91 | + .get('/414', () => { |
| 92 | + throw new UriTooLongException('The URI provided was too long'); |
| 93 | + }) |
| 94 | + .get('/415', () => { |
| 95 | + throw new UnsupportedMediaTypeException('Unsupported media type'); |
| 96 | + }) |
| 97 | + .get('/416', () => { |
| 98 | + throw new RangeNotSatisfiableException('Requested range not satisfiable'); |
| 99 | + }) |
| 100 | + .get('/417', () => { |
| 101 | + throw new ExpectationFailedException('Expectation failed'); |
| 102 | + }) |
| 103 | + .get('/418', () => { |
| 104 | + throw new ImATeapotException("I'm a teapot - cannot brew coffee!"); |
| 105 | + }) |
| 106 | + .get('/421', () => { |
| 107 | + throw new MisdirectedRequestException('Request was misdirected'); |
| 108 | + }) |
| 109 | + .get('/422', () => { |
| 110 | + throw new UnprocessableEntityException('The request was well-formed but contains semantic errors'); |
| 111 | + }) |
| 112 | + .get('/423', () => { |
| 113 | + throw new LockedException('The resource is locked'); |
| 114 | + }) |
| 115 | + .get('/424', () => { |
| 116 | + throw new FailedDependencyException('Request failed due to dependency failure'); |
| 117 | + }) |
| 118 | + .get('/425', () => { |
| 119 | + throw new TooEarlyException('Too early to process this request'); |
| 120 | + }) |
| 121 | + .get('/426', () => { |
| 122 | + throw new UpgradeRequiredException('Client should upgrade to different protocol'); |
| 123 | + }) |
| 124 | + .get('/428', () => { |
| 125 | + throw new PreconditionRequiredException('Precondition is required'); |
| 126 | + }) |
| 127 | + .get('/429', () => { |
| 128 | + throw new TooManyRequestsException('Too many requests - rate limit exceeded'); |
| 129 | + }) |
| 130 | + .get('/431', () => { |
| 131 | + throw new RequestHeaderFieldsTooLargeException('Request header fields too large'); |
| 132 | + }) |
| 133 | + .get('/451', () => { |
| 134 | + throw new UnavailableForLegalReasonsException('Unavailable for legal reasons'); |
| 135 | + }) |
| 136 | + |
| 137 | + // 5xx Server Errors |
| 138 | + .get('/500', () => { |
| 139 | + throw new InternalServerErrorException('An internal server error occurred'); |
| 140 | + }) |
| 141 | + .get('/501', () => { |
| 142 | + throw new NotImplementedException('This functionality is not implemented'); |
| 143 | + }) |
| 144 | + .get('/502', () => { |
| 145 | + throw new BadGatewayException('Bad gateway response from upstream server'); |
| 146 | + }) |
| 147 | + .get('/503', () => { |
| 148 | + throw new ServiceUnavailableException('Service temporarily unavailable'); |
| 149 | + }) |
| 150 | + .get('/504', () => { |
| 151 | + throw new GatewayTimeoutException('Gateway timeout from upstream server'); |
| 152 | + }) |
| 153 | + .get('/505', () => { |
| 154 | + throw new HttpVersionNotSupportedException('HTTP version not supported'); |
| 155 | + }) |
| 156 | + .get('/506', () => { |
| 157 | + throw new VariantAlsoNegotiatesException('Variant also negotiates'); |
| 158 | + }) |
| 159 | + .get('/507', () => { |
| 160 | + throw new InsufficientStorageException('Insufficient storage space'); |
| 161 | + }) |
| 162 | + .get('/508', () => { |
| 163 | + throw new LoopDetectedException('Infinite loop detected'); |
| 164 | + }) |
| 165 | + .get('/510', () => { |
| 166 | + throw new NotExtendedException('Further extensions are required'); |
| 167 | + }) |
| 168 | + .get('/511', () => { |
| 169 | + throw new NetworkAuthenticationRequiredException('Network authentication required'); |
| 170 | + }) |
| 171 | + |
| 172 | + // Examples with custom data/objects |
| 173 | + .get('/custom-error', () => { |
| 174 | + throw new BadRequestException({ |
| 175 | + error: 'VALIDATION_FAILED', |
| 176 | + details: { |
| 177 | + field: 'email', |
| 178 | + message: 'Invalid email format' |
| 179 | + }, |
| 180 | + timestamp: new Date().toISOString() |
| 181 | + }); |
| 182 | + }) |
| 183 | + |
| 184 | + .get('/custom-string', () => { |
| 185 | + throw new NotFoundException('User with ID "12345" not found in the system'); |
| 186 | + }) |
| 187 | + |
| 188 | + .get('/custom-error-object', () => { |
| 189 | + const validationError = new Error('Validation failed for input data'); |
| 190 | + throw new UnprocessableEntityException(validationError); |
| 191 | + }) |
| 192 | + |
| 193 | + // Practical example - User management |
| 194 | + .get('/users/:id', ({ params }) => { |
| 195 | + const userId = parseInt(params.id); |
| 196 | + |
| 197 | + if (isNaN(userId)) { |
| 198 | + throw new BadRequestException('User ID must be a valid number'); |
| 199 | + } |
| 200 | + |
| 201 | + if (userId < 1) { |
| 202 | + throw new BadRequestException('User ID must be positive'); |
| 203 | + } |
| 204 | + |
| 205 | + if (userId === 404) { |
| 206 | + throw new NotFoundException(`User with ID ${userId} not found`); |
| 207 | + } |
| 208 | + |
| 209 | + if (userId === 403) { |
| 210 | + throw new ForbiddenException('You do not have permission to view this user'); |
| 211 | + } |
| 212 | + |
| 213 | + return { id: userId, name: `User ${userId}`, email: `user${userId}@example.com` }; |
| 214 | + }) |
| 215 | + |
| 216 | + // API rate limiting example |
| 217 | + .get('/api/data', ({ request }) => { |
| 218 | + const rateLimitExceeded = Math.random() > 0.7; // Simulate rate limiting |
| 219 | + |
| 220 | + if (rateLimitExceeded) { |
| 221 | + throw new TooManyRequestsException({ |
| 222 | + message: 'Rate limit exceeded', |
| 223 | + retryAfter: 60, |
| 224 | + limit: 100, |
| 225 | + remaining: 0 |
| 226 | + }); |
| 227 | + } |
| 228 | + |
| 229 | + return { data: 'Some API data', timestamp: Date.now() }; |
| 230 | + }) |
| 231 | + |
| 232 | + // Database connection example |
| 233 | + .get('/database/status', () => { |
| 234 | + const dbConnected = Math.random() > 0.3; // Simulate database connection |
| 235 | + |
| 236 | + if (!dbConnected) { |
| 237 | + throw new ServiceUnavailableException('Database connection failed - please try again later'); |
| 238 | + } |
| 239 | + |
| 240 | + return { status: 'Database is healthy', connections: 25 }; |
| 241 | + }) |
| 242 | + |
| 243 | + .listen(3000); |
| 244 | + |
| 245 | +console.log(`🚀 Server is running at http://localhost:3000`); |
| 246 | + |
| 247 | +console.log('\n📚 Available endpoints:'); |
| 248 | +console.log('GET / - Welcome message'); |
| 249 | +console.log('\n🔴 4xx Client Errors:'); |
| 250 | +console.log('GET /400, /401, /402, /403, /404, /405, /406, /408, /409, /410'); |
| 251 | +console.log('GET /411, /412, /413, /414, /415, /416, /417, /418, /421, /422'); |
| 252 | +console.log('GET /423, /424, /425, /426, /428, /429, /431, /451'); |
| 253 | +console.log('\n🔥 5xx Server Errors:'); |
| 254 | +console.log('GET /500, /501, /502, /503, /504, /505, /506, /507, /508, /510, /511'); |
| 255 | +console.log('\n🎯 Custom Examples:'); |
| 256 | +console.log('GET /custom-error - Custom error with object data'); |
| 257 | +console.log('GET /custom-string - Custom error with string message'); |
| 258 | +console.log('GET /custom-error-object - Custom error with Error object'); |
| 259 | +console.log('\n💡 Practical Examples:'); |
| 260 | +console.log('GET /users/:id - User management with validation'); |
| 261 | +console.log('GET /api/data - API rate limiting example'); |
| 262 | +console.log('GET /database/status - Database connection example'); |
0 commit comments