finalhandler

repository·master·Indexed 42 days ago

https://github.com/pillarjs/finalhandler

A Node.js utility used as the final step in an HTTP request lifecycle to respond to requests, handle 404s, and manage error responses gracefully. Version 2.1.1 provides configurable environment settings to prevent leaking error stacks in production and an optional onerror callback for centralized logging.

Tokens
2K
Snippets
8
Records
9
Agent score
4%

What's inside finalhandler

  1. Configure finalhandler options

    master

    When calling finalhandler(req, res, options), you can provide the following configuration keys:

    • options.env: Determines the environment. Defaults to the value of the NODE_ENV environment variable. Use 'production' to ensure error stacks are not leaked in the response body.
    • options.onerror: A function called when an error occurs. This is useful for centralized logging. The function is called with the signature onerror(err, req, res).
  2. Example: Perform simple file operations with error handling

    master

    Use the returned handler to catch errors during asynchronous operations like reading files.

    const finalhandler = require('finalhandler')
    const fs = require('fs')
    const http = require('http')
    
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res)
    
      fs.readFile('index.html', (err, buf) => {
        if (err) return done(err)
        res.setHeader('Content-Type', 'text/html')
        res.end(buf)
      })
    })
    
    server.listen(3000)
  3. Example: Keep a log of all errors using onerror

    master

    Use the onerror option to intercept errors for logging purposes without generating new functions on every request.

    const finalhandler = require('finalhandler')
    const fs = require('fs')
    const http = require('http')
    
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res, { onerror: logerror })
    
      fs.readFile('index.html', (err, buf) => {
        if (err) return done(err)
        res.setHeader('Content-Type', 'text/html')
        res.end(buf)
      })
    })
    
    server.listen(3000)
    
    function logerror (err) {
      console.error(err.stack || err.toString())
    }
  4. Example: Use with middleware-style functions

    master

    Pass the finalhandler instance as the next callback to middleware functions (like serve-static) to ensure they can signal the end of the request chain.

    const finalhandler = require('finalhandler')
    const http = require('http')
    const serveStatic = require('serve-static')
    
    const serve = serveStatic('public')
    
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res)
      serve(req, res, done)
    })
    
    server.listen(3000)
  5. Example: Always return a 404

    master

    If you want to ensure every request that reaches the end of your logic results in a 404, invoke the handler without an error.

    const finalhandler = require('finalhandler')
    const http = require('http')
    
    const server = http.createServer((req, res) => {
      const done = finalhandler(req, res)
      done()
    })
    
    server.listen(3000)
  6. Use finalhandler(req, res, [options])

    master

    The finalhandler function returns a function that should be invoked as the final step of an HTTP request lifecycle. This returned function is called as fn(err).

    • If err is falsy: The handler writes a 404 response to the res object.
    • If err is truthy: An error response is written to res. If a response has already started, res will be terminated.

    Error Response Behavior:

    • res.statusCode: Set from err.status or err.statusCode. If the value is not in the 4xx or 5xx range, it defaults to 500.
    • res.statusMessage: Set according to the status code.
    • Body Content: If options.env is 'production', the body is the HTML of the status code message. Otherwise, the body contains err.stack.
    • Headers: Any headers specified in an err.headers object are applied.

    Side Effects: The handler will unpipe anything from req when it is invoked.

    const finalhandler = require('finalhandler')
    
    // Returns a function 'done'
    const done = finalhandler(req, res, options)
    
    // Invoke it as the final step
    done(err)
  7. Use finalhandler(req, res, [options]) to handle final responses

    master

    The finalhandler function creates a handler for the final step of an HTTP response. It is typically used in middleware stacks to catch unhandled errors or to provide a default 404 response when no other middleware handles the request.

    Behavior

    • If an error is passed to the returned function: It attempts to use the error's status code (err.status or err.statusCode) and headers (err.headers). If no valid status is found, it falls back to the response's current status code (defaulting to 500 if invalid). In non-production environments, the error stack is sent as the response body.
    • If no error is passed: It returns a 404 Not Found response with a message indicating the method and resource (e.g., Cannot GET /path).
    • Safety: If headers have already been sent, it will not attempt to send a new response but will destroy the socket if an error occurred to prevent hanging.

    Options

    • env: The environment string (e.g., 'production'). If not set, it defaults to process.env.NODE_ENV or 'development'. In non-production environments, error stacks are included in the response body.
    • onerror: A callback function invoked when an error is handled. It is called with (err, req, res) using setImmediate.
    const finalhandler = require('finalhandler')
    const http = require('http')
    
    const server = http.createServer((req, res) => {
      // Create the handler
      const done = finalhandler(req, res, {
        onerror: (err, req, res) => {
          console.error('Unhandled error:', err)
        }
      })
    
      // Example usage in a middleware-like pattern
      // If an error occurs, pass it to 'done'
      // If no error occurs, call 'done()' to trigger a 404
      done(new Error('Something went wrong'))
    })
    
    server.listen(3000)
  8. Configure the onerror callback in finalhandler

    master

    You can provide an onerror function in the options object passed to finalhandler. This callback is executed asynchronously via setImmediate whenever an error is passed to the handler. This is useful for logging errors to external services or internal monitoring tools without blocking the response flow.

    The callback signature is (err, req, res).

    const handler = finalhandler(req, res, {
      onerror: (err, req, res) => {
        // Log error to your monitoring service
        myLogger.error(err, { url: req.url })
      }
    })
    
    // Trigger the error handler
    handler(new Error('Database connection failed'))