### Digest Authentication Challenge Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example of setting up a WWW-Authenticate header for Digest authentication challenges. ```javascript const boom = require('@hapi/boom'); const err = boom.unauthorized('Credentials required', 'Digest', { realm: 'protected', qop: 'auth', nonce: '...' }); ``` -------------------------------- ### Bearer Token Authentication Challenge Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example of setting up a WWW-Authenticate header for Bearer token authentication challenges. ```javascript const boom = require('@hapi/boom'); const err = boom.unauthorized('Missing or invalid token', 'Bearer', { realm: 'api' }); ``` -------------------------------- ### Create a 410 Gone Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use this when a resource is permanently unavailable. The example shows how to create the error and log its status code. ```javascript const err = Boom.resourceGone('The requested resource has been deleted'); console.log(err.output.statusCode); // 410 ``` -------------------------------- ### Example of Missing vs. Invalid Authentication Source: https://github.com/hapijs/boom/blob/master/_autodocs/types.md Demonstrates how to differentiate between missing and invalid authentication using `Boom.unauthorized`. The `isMissing` property is true when no credentials are provided. ```javascript const err = Boom.unauthorized(null, 'Bearer'); console.log(err.isMissing); // true (no credentials provided) const err2 = Boom.unauthorized('Expired token', 'Bearer'); console.log(err2.isMissing); // false (credentials provided but invalid) ``` -------------------------------- ### Example Unauthorized Attributes for WWW-Authenticate Header Source: https://github.com/hapijs/boom/blob/master/_autodocs/types.md Shows how to define attributes for the WWW-Authenticate header when creating an unauthorized Boom error. ```javascript const attrs = { realm: 'api.example.com', nonce: 'dcd98b7102dd2f0e8b11d0f600bfb0c093', qop: 'auth' }; const err = Boom.unauthorized('Invalid digest', 'Digest', attrs); // Header: Digest realm="api.example.com", nonce="...", qop="auth", error="Invalid digest" ``` -------------------------------- ### Example Boom Output Object Source: https://github.com/hapijs/boom/blob/master/_autodocs/types.md Demonstrates how to access the output property of a Boom error object to view the formatted HTTP response. ```javascript const err = Boom.methodNotAllowed('POST not supported', undefined, ['GET', 'PUT']); console.log(err.output); // { // statusCode: 405, // headers: { Allow: 'GET, PUT' }, // payload: { // statusCode: 405, // error: 'Method Not Allowed', // message: 'POST not supported' // } // } ``` -------------------------------- ### Hapi Framework Route with Boom Error Handling Source: https://github.com/hapijs/boom/blob/master/_autodocs/00_START_HERE.md This example shows how to integrate Boom with Hapi by throwing a Boom error within a route handler. Hapi automatically catches and processes these errors. ```javascript const Hapi = require('@hapi/hapi'); const Boom = require('@hapi/boom'); const server = Hapi.server({ port: 3000 }); server.route({ method: 'GET', path: '/post/{id}', handler: (request, h) => { const post = findPost(request.params.id); if (!post) throw Boom.notFound('Post not found'); return post; } }); ``` -------------------------------- ### Create a 412 Precondition Failed Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use this when a conditional request header fails validation. The example shows how to generate the error and verify its status code. ```javascript const err = Boom.preconditionFailed('ETag mismatch'); console.log(err.output.statusCode); // 412 ``` -------------------------------- ### Check User Permissions Source: https://github.com/hapijs/boom/blob/master/_autodocs/USAGE_PATTERNS.md This pattern verifies if a user is authenticated and possesses the necessary permissions for a given action and resource. It throws Boom.unauthorized for missing authentication and Boom.forbidden for insufficient permissions. Includes an example of how to catch and handle these errors. ```javascript function authorize(user, action, resource) { if (!user) { throw Boom.unauthorized('Authentication required'); } const permissions = user.permissions || []; if (!permissions.includes(action)) { throw Boom.forbidden(`Insufficient permissions for ${action}`, { action, userPermissions: permissions }); } } // Usage try { authorize(req.user, 'delete', 'post'); } catch (err) { if (Boom.isBoom(err, 403)) { // Handle forbidden error } } ``` -------------------------------- ### Create a 411 Length Required Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use this when a Content-Length header is missing and required by the server. The example demonstrates creating the error and checking its status code. ```javascript const err = Boom.lengthRequired('Content-Length header required'); console.log(err.output.statusCode); // 411 ``` -------------------------------- ### Boom with Custom Error Data Example Source: https://github.com/hapijs/boom/blob/master/_autodocs/types.md Demonstrates creating a Boom error instance with custom typed data. This allows for type-safe access to the attached error context. ```typescript interface ErrorContext { userId: string; timestamp: Date; } const err = new Boom('User action failed', { statusCode: 400, data: { userId: '12345', timestamp: new Date() } }); // Type-safe access to data console.log(err.data.userId); // string ``` -------------------------------- ### Create and Send a Bad Request Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/00_START_HERE.md This snippet demonstrates how to create a 400 Bad Request error using Boom.badRequest and how to send it as an HTTP response. Ensure you have @hapi/boom installed and required. ```javascript const Boom = require('@hapi/boom'); // Create a 400 Bad Request error const err = Boom.badRequest('Invalid email format'); // Send as HTTP response res.status(err.output.statusCode) .json(err.output.payload); ``` -------------------------------- ### HTTP Errors (4xx) Source: https://github.com/hapijs/boom/blob/master/_autodocs/INDEX.md Reference for 22 client-side HTTP error helper functions, covering status codes 400-451. Includes functions like `badRequest()`, `unauthorized()`, `forbidden()`, `notFound()`, `methodNotAllowed()`, with details on parameters, examples, and special handling for `unauthorized()`'s WWW-Authenticate header. ```APIDOC ## HTTP Errors (4xx) ### Description Helper functions for creating 4xx client-side HTTP errors. ### Functions - **badRequest([message], [data])**: Creates a 400 Bad Request error. - **unauthorized([message], [scheme], [attributes], [data])**: Creates a 401 Unauthorized error. Supports `scheme` and `attributes` for WWW-Authenticate header. - **forbidden([message], [data])**: Creates a 403 Forbidden error. - **notFound([message], [data])**: Creates a 404 Not Found error. - **methodNotAllowed([message], [data])**: Creates a 405 Method Not Allowed error. *(... and 17 other 4xx error helpers)* ### Parameters for `unauthorized` - **message** (string, optional) - The error message. - **scheme** (string, optional) - The authentication scheme (e.g., 'Basic', 'Bearer'). - **attributes** (object, optional) - Attributes for the WWW-Authenticate header. - **data** (any, optional) - Additional data. ``` -------------------------------- ### Verify specific Boom error types by status code Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/utility-functions.md This example shows how to use `isBoom` with a status code to differentiate between various types of Boom errors, such as unauthorized (401) and forbidden (403). ```javascript const err1 = Boom.unauthorized('Invalid credentials'); const err2 = Boom.forbidden('Access denied'); console.log(Boom.isBoom(err1, 401)); // true console.log(Boom.isBoom(err1, 403)); // false console.log(Boom.isBoom(err2, 403)); // true ``` -------------------------------- ### Generate 407 Proxy Authentication Required Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.proxyAuthRequired to indicate missing proxy credentials. The example demonstrates creating the error and verifying its status code. ```javascript const err = Boom.proxyAuthRequired('Proxy credentials missing'); console.log(err.output.statusCode); // 407 ``` -------------------------------- ### Boom Status Code Coercion Examples Source: https://github.com/hapijs/boom/blob/master/_autodocs/errors.md Demonstrates how Boom coerces status codes provided as strings. String numbers are converted, decimal strings are truncated, and non-numeric strings result in NaN. ```javascript new Boom.Boom('error', { statusCode: '400' }); new Boom.Boom('error', { statusCode: '400.5' }); ``` ```javascript new Boom.Boom('error', { statusCode: 'abc' }); // NaN assertion error new Boom.Boom('error', { statusCode: 399 }); // <400 assertion error new Boom.Boom('error', { statusCode: null }); // NaN assertion error ``` -------------------------------- ### Rate Limiting Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example of returning a Boom tooManyRequests error for rate limiting. ```javascript const boom = require('@hapi/boom'); // Check rate limit if (request.rateLimitExceeded) { return boom.tooManyRequests('Rate limit exceeded. Try again later.'); } ``` -------------------------------- ### Boom Class and Constructor Source: https://github.com/hapijs/boom/blob/master/_autodocs/INDEX.md Documentation for the `Boom` class, its constructor, instance properties like `isBoom`, `isServer`, `message`, `output`, `data`, `typeof`, and the `reformat(debug?)` instance method, along with details on JSON serialization. ```APIDOC ## Class: Boom ### Description Represents an HTTP-friendly error object. ### Properties - **isBoom** (boolean) - Indicates if the object is a Boom instance. - **isServer** (boolean) - Indicates if the error is a server-side error. - **message** (string) - The error message. - **output** (object) - The output representation of the error. - **data** (any) - Additional data associated with the error. - **typeof** (string) - The type of the error. ### Methods - **reformat(debug?)** (function) - Reformats the error output. `debug` (boolean, optional) - If true, includes debug information. ### JSON Serialization Boom objects are JSON serializable. ``` -------------------------------- ### Error Aggregation in Validation Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example of aggregating multiple validation errors into a single Boom response. ```javascript const boom = require('@hapi/boom'); const errors = [ { field: 'email', message: 'Invalid format' }, { field: 'password', message: 'Too short' } ]; const err = boom.badData('Multiple validation errors', errors); ``` -------------------------------- ### Multiple Authentication Schemes Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to specify multiple authentication schemes in the WWW-Authenticate header. ```javascript const boom = require('@hapi/boom'); const err = boom.unauthorized('Authentication required', ['Bearer', 'Basic'], { realm: 'api' }); ``` -------------------------------- ### Form Validation with Joi Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Example of using Boom with Joi for form validation, returning a 422 Unprocessable Entity error. ```javascript const boom = require('@hapi/boom'); const Joi = require('joi'); const schema = Joi.object({ username: Joi.string().alphanum().min(3).max(30).required() }); const { error } = schema.validate(request.payload); if (error) { return boom.badData('Invalid input', error.details); } ``` -------------------------------- ### Create and Test Basic Errors (JavaScript) Source: https://github.com/hapijs/boom/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to create and assert properties of common Boom errors like badRequest and unauthorized. Requires @hapi/lab for testing. ```javascript const lab = require('@hapi/lab'); const Boom = require('@hapi/boom'); const { describe, it } = exports.lab = lab.script(); describe('Error handling', () => { it('creates badRequest error', () => { const err = Boom.badRequest('Invalid input'); assert(Boom.isBoom(err)); assert(err.output.statusCode === 400); assert(err.message === 'Invalid input'); }); it('creates unauthorized error with scheme', () => { const err = Boom.unauthorized('Invalid token', 'Bearer'); assert(Boom.isBoom(err, 401)); assert(err.output.headers['WWW-Authenticate']); }); }); ``` -------------------------------- ### Missing vs. Invalid Credentials Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to differentiate between missing and invalid credentials in authentication errors. ```javascript const boom = require('@hapi/boom'); // Missing credentials const missingErr = boom.unauthorized('Missing credentials'); // Invalid credentials const invalidErr = boom.unauthorized('Invalid credentials'); ``` -------------------------------- ### Generate 429 Too Many Requests Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.tooManyRequests() for rate limiting purposes. This example shows how to generate the error and log its status code. ```javascript const err = Boom.tooManyRequests('Rate limit exceeded: 100 requests per minute'); console.log(err.output.statusCode); // 429 ``` -------------------------------- ### Boom.notImplemented Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 501 Not Implemented error. Use this when the requested functionality is not yet supported by the server. ```javascript Boom.notImplemented('method not implemented'); ``` -------------------------------- ### Generate 451 Unavailable For Legal Reasons Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.illegal() when content is unavailable for legal reasons. This example creates the error and logs its status code. ```javascript const err = Boom.illegal('Content unavailable due to legal restrictions'); console.log(err.output.statusCode); // 451 ``` -------------------------------- ### Boom.illegal Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 451 Unavailable For Legal Reasons error. Use this when a resource cannot be provided due to legal restrictions. ```javascript Boom.illegal('you are not permitted to view this resource for legal reasons'); ``` -------------------------------- ### Hapi Framework Integration Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates how Boom errors are automatically handled within the Hapi framework. ```javascript server.route({ method: 'GET', path: '/test', handler: function (request, h) { return boom.badRequest('This is a test'); } }); ``` -------------------------------- ### Generate 425 Too Early Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.tooEarly() when the server is unwilling to risk processing the request. This example shows how to create the error and log its status code. ```javascript const err = Boom.tooEarly('Request too early for processing'); console.log(err.output.statusCode); // 425 ``` -------------------------------- ### Method Not Allowed with Allow Headers Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to return a 405 Method Not Allowed error and include the 'Allow' header. ```javascript const boom = require('@hapi/boom'); // Assume only GET and POST are allowed const allowedMethods = ['GET', 'POST']; // When a PUT request is made: const err = boom.methodNotAllowed('Method not supported'); err.output.headers['Allow'] = allowedMethods.join(', '); ``` -------------------------------- ### Generate 409 Conflict Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.conflict when a request conflicts with the current state of a resource. The example illustrates creating the error and logging its status code. ```javascript const err = Boom.conflict('Version conflict - resource was modified'); console.log(err.output.statusCode); // 409 ``` -------------------------------- ### Create Not Found Error (404) Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use `Boom.notFound()` to generate a 404 Not Found error. This is appropriate when the client requests a resource that does not exist on the server. ```javascript const err = Boom.notFound('User profile not found'); console.log(err.output.statusCode); // 404 ``` -------------------------------- ### Generate 428 Precondition Required Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.preconditionRequired() when the request must include a conditional header. This example demonstrates creating the error and checking its status code. ```javascript const err = Boom.preconditionRequired('If-Match header required'); console.log(err.output.statusCode); // 428 ``` -------------------------------- ### Basic Error Creation with Message Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates the simplest way to create a Boom error with a custom message. ```javascript const boom = require('@hapi/boom'); const err = boom.badRequest('Missing required field'); ``` -------------------------------- ### Generate 408 Request Time-out Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.clientTimeout when the server times out waiting for a client request. The example shows how to generate this error and check its status code. ```javascript const err = Boom.clientTimeout('Request took too long'); console.log(err.output.statusCode); // 408 ``` -------------------------------- ### Stack Trace Filtering with ctor Option Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to filter stack traces by providing a constructor option when creating Boom errors. ```javascript const boom = require('@hapi/boom'); const err = boom.internal('Operation failed', { ctor: 'MyService' }); ``` -------------------------------- ### Boom.notImplemented Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 501 Not Implemented error. Optionally accepts a message and additional data. ```APIDOC ## Boom.notImplemented ### Description Returns a 501 Not Implemented error. ### Method `Boom.notImplemented([message], [data])` ### Parameters #### Arguments - **message** (string) - Optional message for the error. - **data** (any) - Optional additional error data. ### Request Example ```js Boom.notImplemented('method not implemented'); ``` ### Response #### Success Response (501) ```json { "statusCode": 501, "error": "Not Implemented", "message": "method not implemented" } ``` ``` -------------------------------- ### Generate 406 Not Acceptable Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use Boom.notAcceptable when the server cannot fulfill client Accept header preferences. The example shows how to create the error and log its status code. ```javascript const err = Boom.notAcceptable('Only JSON supported'); console.log(err.output.statusCode); // 406 ``` -------------------------------- ### Boom.serverUnavailable Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 503 Service Unavailable error. Use this when the server is temporarily unable to handle the request. ```javascript Boom.serverUnavailable('unavailable'); ``` -------------------------------- ### Create a 413 Entity Too Large Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use this when the request body exceeds the server's size limits. The example illustrates creating the error and logging its status code. ```javascript const err = Boom.entityTooLarge('File too large (max 10MB)'); console.log(err.output.statusCode); // 413 ``` -------------------------------- ### Implement Simple Rate Limiter Source: https://github.com/hapijs/boom/blob/master/_autodocs/USAGE_PATTERNS.md Use this pattern to track request counts per client IP and throw a Boom.tooManyRequests error if the limit is exceeded within a minute. Requires a Map to store request counts. ```javascript const requestCounts = new Map(); const LIMIT_PER_MINUTE = 60; function checkRateLimit(clientIp) { const count = requestCounts.get(clientIp) || 0; if (count >= LIMIT_PER_MINUTE) { throw Boom.tooManyRequests('Rate limit exceeded', { limit: LIMIT_PER_MINUTE, window: '1 minute' }); } requestCounts.set(clientIp, count + 1); } ``` -------------------------------- ### Error Chaining with Boom Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates how to chain Boom errors, preserving the original error context. ```javascript const boom = require('@hapi/boom'); try { throw boom.badRequest('Initial error'); } catch (err) { const chainedErr = boom.internal('Processing failed', err); throw chainedErr; } ``` -------------------------------- ### notFound Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Returns a 404 Not Found error. This is used when the requested resource does not exist on the server. ```APIDOC ## `notFound(message?, data?)` ### Description Returns a 404 Not Found error. Use when a requested resource does not exist. ### Method ```typescript function notFound(messageOrError?: string | Error, data?: Data): Boom ``` ### Example ```javascript const err = Boom.notFound('User profile not found'); console.log(err.output.statusCode); // 404 ``` ``` -------------------------------- ### Wrap Async Errors with Boom.badGateway Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-5xx.md Demonstrates how to wrap unexpected errors from asynchronous operations into a Boom.badGateway error, preserving relevant context. ```javascript async function processPayment(orderId) { try { return await paymentGateway.charge(orderId); } catch (err) { // Wrap unexpected errors as 5xx (server error) throw Boom.badGateway('Payment processing failed', { orderId, originalMessage: err.message }); } } ``` -------------------------------- ### Resource Lookup Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to return a Boom notFound error when a requested resource does not exist. ```javascript const boom = require('@hapi/boom'); async function getResource(id) { const resource = await db.findResource(id); if (!resource) { throw boom.notFound(`Resource with id ${id} not found.`); } return resource; } ``` -------------------------------- ### Handling Timeouts Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates creating a Boom gateway timeout error when an operation exceeds its allowed time. ```javascript const boom = require('@hapi/boom'); // Assume timeoutPromise rejects after a certain time timeoutPromise.catch(err => { throw boom.gatewayTimeout('Operation timed out', err); }); ``` -------------------------------- ### serverUnavailable Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-5xx.md Returns a 503 Service Unavailable error. Use when the service is temporarily down or overloaded. ```APIDOC ## `serverUnavailable(message?, data?)` ### Description Returns a 503 Service Unavailable error. Use when the service is temporarily down or overloaded. ### Method N/A (Function Signature) ### Parameters #### Arguments - **messageOrError** (string | Error) - Optional - Error message or Error object. - **data** (Data) - Optional - Custom error data. ### Response #### Return Value A `Boom` object with status code 503. ### Example ```javascript const err = Boom.serverUnavailable('Server overloaded - try again later', { activeConnections: 10000, maxCapacity: 8000, retryAfterSeconds: 120 }); console.log(err.output.statusCode); // 503 ``` ``` -------------------------------- ### notImplemented Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-5xx.md Returns a 501 Not Implemented error. Use when a feature or endpoint is not yet implemented. ```APIDOC ## `notImplemented(message?, data?)` ### Description Returns a 501 Not Implemented error. Use when a feature or endpoint is not yet implemented. ### Method Signature ```typescript function notImplemented(messageOrError?: string | Error, data?: Data): Boom ``` ### Parameters #### Arguments - **messageOrError** (`string | Error`) - Optional - Error message or Error object. - **data** (`Data`) - Optional - Custom error data. ### Return Value A `Boom` object with status code 501. ### Example ```javascript const err = Boom.notImplemented('Scheduled maintenance endpoint not ready'); console.log(err.output.statusCode); // 501 ``` ``` -------------------------------- ### Boom.serverUnavailable Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 503 Service Unavailable error. Optionally accepts a message and additional data. ```APIDOC ## Boom.serverUnavailable ### Description Returns a 503 Service Unavailable error. ### Method `Boom.serverUnavailable([message], [data])` ### Parameters #### Arguments - **message** (string) - Optional message for the error. - **data** (any) - Optional additional error data. ### Request Example ```js Boom.serverUnavailable('unavailable'); ``` ### Response #### Success Response (503) ```json { "statusCode": 503, "error": "Service Unavailable", "message": "unavailable" } ``` ``` -------------------------------- ### resourceGone Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Returns a 410 Gone error. Use when the requested resource is no longer available and will not be available again. ```APIDOC ## `resourceGone(message?, data?)` ### Description Returns a 410 Gone error. Use when the requested resource is no longer available and will not be available again. ### Method N/A (This is a function signature, not an HTTP endpoint) ### Parameters - **message** (string | Error) - Optional - The error message or an Error object. - **data** (any) - Optional - Additional data to include with the error. ### Example ```javascript const err = Boom.resourceGone('The requested resource has been deleted'); console.log(err.output.statusCode); // 410 ``` ``` -------------------------------- ### Create Server Errors (5xx) Source: https://github.com/hapijs/boom/blob/master/_autodocs/REFERENCE.md Utilize Boom.internal, Boom.badGateway, and Boom.badImplementation for server-side errors. The reformat(true) method can be used to display the actual error message in debug mode. ```javascript // Generic server error const err = Boom.internal('Database connection failed'); // Specific server error const err2 = Boom.badGateway('Upstream API returned 500'); // Developer error const err3 = Boom.badImplementation('Logic bug in request handler'); // Show actual message in debug mode err.reformat(true); ``` -------------------------------- ### Boom Constructor and Decorator Methods Source: https://github.com/hapijs/boom/blob/master/API.md This section covers the core methods for creating and decorating errors with Boom properties. `Boom.Boom(message, [options])` creates a new Boom object, while `boomify(err, [options])` decorates an existing error. ```APIDOC ## Boom Constructor and Decorator Methods ### Description This section covers the core methods for creating and decorating errors with Boom properties. `Boom.Boom(message, [options])` creates a new Boom object, while `boomify(err, [options])` decorates an existing error. ### `new Boom.Boom(message, [options])` Creates a new `Boom` object using the provided `message` and then calling [`boomify()`](#boomifyerr-options) to decorate the error with the `Boom` properties, where: - `message` - the error message. If `message` is an error, it is the same as calling [`boomify()`](#boomifyerr-options) directly. - `options` - and optional object where: - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set. - `data` - additional error information (assigned to `error.data`). - `decorate` - an option with extra properties to set on the error object. - `ctor` - constructor reference used to crop the exception call stack output. - if `message` is an error object, also supports the other [`boomify()`](#boomifyerr-options) options. ### `boomify(err, [options])` Decorates an error with the `Boom` properties where: - `err` - the `Error` object to decorate. - `options` - optional object with the following optional settings: - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set and `err` is not a `Boom` object. - `message` - error message string. If the error already has a message, the provided `message` is added as a prefix. Defaults to no message. - `decorate` - an option with extra properties to set on the error object. - `override` - if `false`, the `err` provided is a `Boom` object, and a `statusCode` or `message` are provided, the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error regardless of its type, `Error` or `Boom` object). ```js var error = new Error('Unexpected input'); Boom.boomify(error, { statusCode: 400 }); ``` ``` -------------------------------- ### Create Not Found Error Source: https://github.com/hapijs/boom/blob/master/API.md Generates a 404 Not Found error with a custom message. Use this when a requested resource cannot be found. ```javascript Boom.notFound('missing'); ``` -------------------------------- ### unsupportedMediaType Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Returns a 415 Unsupported Media Type error. Use when the request content type is not supported. ```APIDOC ## `unsupportedMediaType(message?, data?)` ### Description Returns a 415 Unsupported Media Type error. Use when the request content type is not supported. ### Method Signature ```typescript function unsupportedMediaType(messageOrError?: string | Error, data?: Data): Boom ``` ### Example ```javascript const err = Boom.unsupportedMediaType('Only application/json supported'); console.log(err.output.statusCode); // 415 ``` ``` -------------------------------- ### Create Basic 500 Internal Server Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-5xx.md Use `Boom.internal()` to create a standard 500 Internal Server Error. The default message is hidden from the client. ```javascript const Boom = require('@hapi/boom'); const err = Boom.internal('Database connection lost'); console.log(err.output.statusCode); // 500 console.log(err.output.payload.message); // "An internal server error occurred" ``` -------------------------------- ### Documentation Structure and Content Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Outlines the organization and components of the Boom documentation, including navigation aids and content details. ```APIDOC ## Document Features ### Description Details the structure, content, and navigation aids provided within the Boom documentation. ### Content Elements - Clear section headings - Purpose statements - Parameter tables (markdown) - Type signatures - Code blocks with language specification - Cross-references between documents - Source file line numbers - Security considerations - Common pitfalls and solutions - Integration examples ### Navigation Aids - README.md quick start - INDEX.md master navigation - REFERENCE.md API summary - Multiple entry points - Consistent internal linking - Use-case-based navigation - Status-code lookup tables ``` -------------------------------- ### Boom.notFound Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 404 Not Found error. It can optionally include a message and additional data. ```APIDOC ## Boom.notFound([message], [data]) ### Description Returns a 404 Not Found error. The `message` is an optional string, and `data` is optional additional error data. ### Method N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js Boom.notFound('missing'); ``` ### Response #### Success Response (404) - **statusCode** (number) - The HTTP status code, always 404. - **error** (string) - The error type, always 'Not Found'. - **message** (string) - The error message provided. - **data** (any) - Additional error data, if provided. #### Response Example ```json { "statusCode": 404, "error": "Not Found", "message": "missing" } ``` ``` -------------------------------- ### Boom.gatewayTimeout Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 504 Gateway Time-out error. Use this when an upstream server did not respond in time. ```javascript Boom.gatewayTimeout(); ``` -------------------------------- ### Implementing Error Recovery with Fallback Source: https://github.com/hapijs/boom/blob/master/_autodocs/USAGE_PATTERNS.md This asynchronous function executes an operation and provides a fallback value if a specific error (e.g., 404 Not Found) occurs. Other errors are re-thrown. Use this pattern to gracefully handle expected, non-critical errors without halting execution. ```javascript async function executeWithFallback(operation, fallbackValue) { try { return await operation(); } catch (err) { if (Boom.isBoom(err, 404)) { // Resource not found - use fallback return fallbackValue; } throw err; // Re-throw other errors } } ``` -------------------------------- ### Boom.resourceGone Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 410 Gone error. Accepts an optional message and additional data. ```APIDOC ## Boom.resourceGone ### Description Returns a 410 Gone error. ### Method ``` Boom.resourceGone([message], [data]) ``` ### Parameters - **message** (string) - Optional - The error message. - **data** (any) - Optional - Additional error data. ### Request Example ```js Boom.resourceGone('it is gone'); ``` ### Response #### Success Response (410) - **statusCode** (number) - The HTTP status code (410). - **error** (string) - The error type ('Gone'). - **message** (string) - The error message provided. #### Response Example ```json { "statusCode": 410, "error": "Gone", "message": "it is gone" } ``` ``` -------------------------------- ### Database Error Handling Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates how to catch and transform database-related errors into Boom internal errors. ```javascript const boom = require('@hapi/boom'); async function getUser(id) { try { const user = await db.users.findById(id); if (!user) { throw boom.notFound('User not found'); } return user; } catch (err) { if (err.isBoom) { throw err; } throw boom.internal('Database error fetching user', err); } } ``` -------------------------------- ### Not Found Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/REFERENCE.md Use Boom.notFound to indicate that a requested resource could not be found. Include the identifier of the missing resource in the message. ```javascript const user = await User.findById(id); if (!user) { throw Boom.notFound(`User ${id} not found`); } ``` -------------------------------- ### Generate Resource Gone Error (410) Source: https://github.com/hapijs/boom/blob/master/API.md Use Boom.resourceGone to create a 410 Gone error. An optional message and data can be provided. ```javascript Boom.resourceGone('it is gone'); ``` -------------------------------- ### Boom.unsupportedMediaType Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 415 Unsupported Media Type error. Accepts an optional message and additional data. ```APIDOC ## Boom.unsupportedMediaType ### Description Returns a 415 Unsupported Media Type error. ### Method ``` Boom.unsupportedMediaType([message], [data]) ``` ### Parameters - **message** (string) - Optional - The error message. - **data** (any) - Optional - Additional error data. ### Request Example ```js Boom.unsupportedMediaType('that media is not supported'); ``` ### Response #### Success Response (415) - **statusCode** (number) - The HTTP status code (415). - **error** (string) - The error type ('Unsupported Media Type'). - **message** (string) - The error message provided. #### Response Example ```json { "statusCode": 415, "error": "Unsupported Media Type", "message": "that media is not supported" } ``` ``` -------------------------------- ### badImplementation Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-5xx.md Returns a 500 Internal Server Error. This is the alias for the primary use case of server-side programming errors. ```APIDOC ## `badImplementation(message?, data?)` ### Description Returns a 500 Internal Server Error. Alias for the primary use case of server-side programming errors. ### Method Signature ```typescript function badImplementation( messageOrError?: string | Error, data?: Data ): Boom ``` ### Parameters #### Arguments - **messageOrError** (`string | Error`) - Optional - Error message or Error object. - **data** (`Data`) - Optional - Custom error data. ### Return Value A `Boom` object with status code 500 and `isDeveloperError` property set to `true`. ### Special Properties The returned error has an `isDeveloperError` flag: ```typescript interface BadImplementationError extends Boom { isDeveloperError: true; } ``` This property can be used to identify developer errors vs. other server errors. ### Example ```javascript const err = Boom.badImplementation('Null pointer in request handler'); console.log(err.isDeveloperError); // true console.log(err.output.payload.message); // "An internal server error occurred" // In development: err.reformat(true); console.log(err.output.payload.message); // "Null pointer in request handler" ``` ``` -------------------------------- ### Boom.badImplementation Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 500 Internal Server Error. This is a general error for unexpected server-side issues. The message is hidden from the client. ```javascript Boom.badImplementation('terrible implementation'); ``` -------------------------------- ### `preconditionRequired(message?, data?)` Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Returns a 428 Precondition Required error. Use when the request must include a conditional header. ```APIDOC ## `preconditionRequired(message?, data?)` ### Description Returns a 428 Precondition Required error. Use when the request must include a conditional header. ### Method N/A (This is a library function, not an HTTP endpoint) ### Parameters - **message** (string | Error) - Optional - The error message or an Error object. - **data** (any) - Optional - Additional data to include with the error. ### Example ```javascript const err = Boom.preconditionRequired('If-Match header required'); console.log(err.output.statusCode); // 428 ``` ``` -------------------------------- ### Boom.tooEarly Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 425 Too Early error. Use this when the server is unwilling to process the request due to its early timing. ```javascript Boom.tooEarly('the server is unwilling to risk processing the request'); ``` -------------------------------- ### Generate Unsupported Media Type Error (415) Source: https://github.com/hapijs/boom/blob/master/API.md Use Boom.unsupportedMediaType to create a 415 Unsupported Media Type error. An optional message and data can be provided. ```javascript Boom.unsupportedMediaType('that media is not supported'); ``` -------------------------------- ### Create Method Not Allowed Error (405) Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Use `Boom.methodNotAllowed()` to create a 405 Method Not Allowed error. This function can also specify allowed HTTP methods via the `allow` parameter, which will be included in the `Allow` header. ```javascript const err = Boom.methodNotAllowed('POST not allowed', undefined, ['GET', 'PUT']); console.log(err.output.headers.Allow); // "GET, PUT" ``` -------------------------------- ### Create Custom 5xx Server Error Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-5xx.md Provide a custom status code (between 500-599) to `Boom.internal()` to represent specific server errors like 'Service Unavailable'. ```javascript const err = Boom.internal('Service not ready', undefined, 503); console.log(err.output.statusCode); // 503 ``` -------------------------------- ### Boom.preconditionRequired Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 428 Precondition Required error. Use this when a required precondition, like an If-Match header, is missing. ```javascript Boom.preconditionRequired('you must supply an If-Match header'); ``` -------------------------------- ### HTTP 5xx Helper Functions Source: https://github.com/hapijs/boom/blob/master/_autodocs/REFERENCE.md Convenience functions for creating common HTTP 5xx errors. ```APIDOC ## HTTP 5xx Helper Functions ### `internal(message?, data?, statusCode?)` #### Description Creates a `500 Internal Server Error`. Allows for custom status codes and data. ### `badImplementation(message?, data?)` #### Description Creates a `500 Internal Server Error` with `isDeveloperError` set to true. ### `notImplemented(message?, data?)` #### Description Creates a `501 Not Implemented` error. ### `badGateway(message?, data?)` #### Description Creates a `502 Bad Gateway` error. ### `serverUnavailable(message?, data?)` #### Description Creates a `503 Service Unavailable` error. ### `gatewayTimeout(message?, data?)` #### Description Creates a `504 Gateway Time-out` error. ``` -------------------------------- ### Custom Headers with Boom Errors Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to add custom headers to a Boom error response. ```javascript const boom = require('@hapi/boom'); const err = boom.unauthorized('Invalid credentials', 'Basic', { realm: 'example' }); err.output.headers['X-Custom-Header'] = 'some-value'; ``` -------------------------------- ### `illegal(message?, data?)` Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/http-errors-4xx.md Returns a 451 Unavailable For Legal Reasons error. Use when content is unavailable for legal reasons. ```APIDOC ## `illegal(message?, data?)` ### Description Returns a 451 Unavailable For Legal Reasons error. Use when content is unavailable for legal reasons. ### Method N/A (This is a library function, not an HTTP endpoint) ### Parameters - **message** (string | Error) - Optional - The error message or an Error object. - **data** (any) - Optional - Additional data to include with the error. ### Example ```javascript const err = Boom.illegal('Content unavailable due to legal restrictions'); console.log(err.output.statusCode); // 451 ``` ``` -------------------------------- ### Multiple Authentication Schemes Challenge Source: https://github.com/hapijs/boom/blob/master/_autodocs/USAGE_PATTERNS.md Use this pattern to throw an unauthorized error when multiple authentication schemes (Bearer, Basic, Digest) are supported. ```javascript const err = Boom.unauthorized(null, ['Bearer', 'Basic', 'Digest']); // Output: // WWW-Authenticate: Bearer, Basic, Digest // isMissing: true (no credentials provided) ``` -------------------------------- ### Boom.badImplementation Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 500 Internal Server Error. This is an alias for `Boom.internal`. Optionally accepts a message and additional data. ```APIDOC ## Boom.badImplementation ### Description Returns a 500 Internal Server Error. All 500 errors hide your message from the end user. ### Method `Boom.badImplementation([message], [data])` ### Parameters #### Arguments - **message** (string) - Optional message for the error. - **data** (any) - Optional additional error data. ### Request Example ```js Boom.badImplementation('terrible implementation'); ``` ### Response #### Success Response (500) ```json { "statusCode": 500, "error": "Internal Server Error", "message": "An internal server error occurred" } ``` ``` -------------------------------- ### Error with Decorations Source: https://github.com/hapijs/boom/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates adding custom properties (decorations) to a Boom error object. ```javascript const boom = require('@hapi/boom'); const err = boom.notFound('Resource not found').output.payload; err.customProperty = 'some value'; ``` -------------------------------- ### Retrieve formatted HTTP response output Source: https://github.com/hapijs/boom/blob/master/_autodocs/api-reference/boom-class.md The `output` property provides a structured object containing `statusCode`, `headers`, and `payload` ready for HTTP responses. Changes to this object are lost if `reformat()` is called. ```javascript const err = Boom.notFound('User not found'); console.log(err.output); // { // statusCode: 404, // headers: {}, // payload: { // statusCode: 404, // error: 'Not Found', // message: 'User not found' // } // } ``` -------------------------------- ### Create Basic Boom Errors Source: https://github.com/hapijs/boom/blob/master/_autodocs/README.md Create client or server errors using Boom's factory methods. The status code is automatically assigned. ```javascript const Boom = require('@hapi/boom'); // Client error const err = Boom.badRequest('Invalid input'); console.log(err.output.statusCode); // 400 // Server error const err2 = Boom.internal('Database failed'); console.log(err2.output.statusCode); // 500 ``` -------------------------------- ### Create Client Errors (4xx) Source: https://github.com/hapijs/boom/blob/master/_autodocs/REFERENCE.md Use Boom.badRequest, Boom.notFound, and Boom.unauthorized to create common client-side HTTP errors. Custom data can be included with the error object. ```javascript const Boom = require('@hapi/boom'); // Simple error const err = Boom.badRequest('Invalid email'); // With custom data const err2 = Boom.notFound('User not found', { userId: '123' }); // With authentication challenge const err3 = Boom.unauthorized('Invalid token', 'Bearer'); ``` -------------------------------- ### HTTP Errors (5xx) Source: https://github.com/hapijs/boom/blob/master/_autodocs/INDEX.md Reference for 6 server-side HTTP error helper functions, covering status codes 500-504. Includes functions like `internal()`, `badImplementation()`, `notImplemented()`, `badGateway()`, `serverUnavailable()`, `gatewayTimeout()`, with details on message hiding for security and the `isDeveloperError` property. ```APIDOC ## HTTP Errors (5xx) ### Description Helper functions for creating 5xx server-side HTTP errors. ### Functions - **internal([message], [data])**: Creates a 500 Internal Server Error. - **badImplementation([message], [data])**: Creates a 500 Internal Server Error, often used for programming errors. - **notImplemented([message], [data])**: Creates a 501 Not Implemented error. - **badGateway([message], [data])**: Creates a 502 Bad Gateway error. - **serverUnavailable([message], [data])**: Creates a 503 Service Unavailable error. - **gatewayTimeout([message], [data])**: Creates a 504 Gateway Timeout error. ### Notes - Error messages for server errors are hidden by default for security. - The `isDeveloperError` property can be set to true to expose more details in development environments. ``` -------------------------------- ### Options Interface Definition Source: https://github.com/hapijs/boom/blob/master/_autodocs/types.md Defines the configuration object for the Boom constructor and the boomify() function. Use this interface to specify options like status code, custom data, and constructor references when creating Boom errors. ```typescript export interface Options { statusCode?: number; data?: Data; ctor?: Function; message?: string; override?: boolean; } ``` -------------------------------- ### Log Errors with Context Source: https://github.com/hapijs/boom/blob/master/_autodocs/USAGE_PATTERNS.md This snippet shows how to log errors, distinguishing between Boom errors and regular JavaScript errors. It includes essential details like timestamp, message, data, stack trace, and status code for Boom errors. ```javascript function logError(err) { const logEntry = { timestamp: new Date().toISOString(), isBoom: Boom.isBoom(err), message: err.message, data: err.data, stack: err.stack }; if (Boom.isBoom(err)) { logEntry.statusCode = err.output.statusCode; logEntry.isServer = err.isServer; } logger.error(logEntry); } ``` -------------------------------- ### Boom.preconditionRequired Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 428 Precondition Required error. Optionally accepts a message and additional data. ```APIDOC ## Boom.preconditionRequired ### Description Returns a 428 Precondition Required error. ### Method `Boom.preconditionRequired([message], [data])` ### Parameters #### Arguments - **message** (string) - Optional message for the error. - **data** (any) - Optional additional error data. ### Request Example ```js Boom.preconditionRequired('you must supply an If-Match header'); ``` ### Response #### Success Response (428) ```json { "statusCode": 428, "error": "Precondition Required", "message": "you must supply an If-Match header" } ``` ``` -------------------------------- ### Generate Precondition Failed Error (412) Source: https://github.com/hapijs/boom/blob/master/API.md Use Boom.preconditionFailed to create a 412 Precondition Failed error. An optional message and data can be provided. ```javascript Boom.preconditionFailed(); ``` -------------------------------- ### Boom.illegal Source: https://github.com/hapijs/boom/blob/master/API.md Returns a 451 Unavailable For Legal Reasons error. Optionally accepts a message and additional data. ```APIDOC ## Boom.illegal ### Description Returns a 451 Unavailable For Legal Reasons error. ### Method `Boom.illegal([message], [data])` ### Parameters #### Arguments - **message** (string) - Optional message for the error. - **data** (any) - Optional additional error data. ### Request Example ```js Boom.illegal('you are not permitted to view this resource for legal reasons'); ``` ### Response #### Success Response (451) ```json { "statusCode": 451, "error": "Unavailable For Legal Reasons", "message": "you are not permitted to view this resource for legal reasons" } ``` ``` -------------------------------- ### Generate Bad Gateway Error for Upstream Service Failure Source: https://github.com/hapijs/boom/blob/master/_autodocs/USAGE_PATTERNS.md Use Boom.badGateway when an upstream service is unavailable. Include the service host and the original error for context. ```javascript async function callUpstream(url) { try { return await fetch(url); } catch (err) { throw Boom.badGateway('Upstream service unavailable', { service: new URL(url).host, originalError: err.message }); } } ``` -------------------------------- ### Options Source: https://github.com/hapijs/boom/blob/master/_autodocs/types.md Configuration object used for creating new Boom errors or when using the `boomify()` function. It allows customization of status codes, data, and other error properties. ```APIDOC ## Options ### Description Configuration object used for creating new Boom errors or when using the `boomify()` function. It allows customization of status codes, data, and other error properties. ### Type Parameter `Data` — The type of custom data to be attached to the error. ### Properties - **statusCode** (number) - Optional. HTTP status code (must be 400+). Defaults to 500 if not provided. - **data** (Data) - Optional. Custom error data attached to the error. - **ctor** (Function) - Optional. Constructor reference for stack trace filtering. - **message** (string) - Optional. Error message string. Prepended to existing message if both are present. - **override** (boolean) - Optional. If `false` and error is already Boom, ignores statusCode and message. Defaults to `true`. ```