const { fail } = require('../utils/response')
const logger = require('../utils/logger')

module.exports = function errorHandler(err, req, res, next) {
    logger.error('接口处理异常', {
        path: req.originalUrl,
        method: req.method,
        error: err.message,
        details: err.details || {},
    })

    if (res.headersSent) {
        return next(err)
    }

    return fail(res, err.statusCode || 500, err.message || '服务器内部错误', {
        ...(err.details || {}),
    })
}
