@sap/cds
Version:
SAP Cloud Application Programming Model - CDS for Node.js
43 lines (34 loc) • 1.75 kB
JavaScript
const cds = require('../..')
/**
* Final error handling middleware, optionally bound to a specific adapter.
* It handles authentication errors (401) and uncaught system errors, and
* normalizes other errors for consistent logging and response formatting.
* @param {import('../protocols/http')} adapter - The HTTP adapter to bind the error middleware to.
*/
module.exports = exports = adapter => adapter ? http_error.bind(adapter) : http_error
/**
* The actual error handling middleware, as used through cds.middlewares.after.
* @type {import('express').ErrorRequestHandler}
* @this {import('../protocols/http')}
*/
function http_error (error, req, res, next) { // eslint-disable-line no-unused-vars
if (error == 401 || error.status == 401 || error.code == 401)
return req._login?.() || res.sendStatus(401)
// Shutdown on uncaught errors, which could be critical programming errors
if (!(typeof global.test === 'function') && cds.env.server.shutdown_on_uncaught_errors)
if (cds.error.isSystemError (error))
return cds.shutdown (error)
// Log the normalized error
const { status = 500 } = error, adapter = this.router ? this : dummy
const log = adapter.logger [status < 500 ? 'warn' : 'error']
log (status, '-', error)
// Finalize and send the error response
if (res.headersSent) return // done by custom code already
return res.status(status).json(adapter.response4({ error }))
}
// Dummy adapter for compatibility, e.g. with GraphQL adapter
const dummy = new class extends require('../protocols/http') {
logger = cds.log('error')
}
// Adjust inspect.depth for better error logging, especially for nested error causes
const { inspect } = require('node:util'); inspect.defaultOptions.depth = 3