【问题标题】:Express 4 - Custom error handling middleware is not being calledExpress 4 - 未调用自定义错误处理中间件
【发布时间】:2020-07-13 14:41:20
【问题描述】:

我正在尝试在我的 Express 应用中实现自定义错误处理程序。我认为我正确地遵循了文档,但我一定做错了,因为我的应用程序在任何时候端点出错时都会返回 HTML。

文档:https://expressjs.com/en/guide/error-handling.html

我在这里和 GitHub 上发现的几乎所有类似问题都已通过放置错误处理中间件和堆栈的最末端来解决......但我已经这样做了,但仍然没有运气。

这是我的代码:

// server.js

import express from 'express';
import body from 'body-parser';
import cookies from 'cookie-parser';
import {
    provideLogger,
    responseStructure,
    errorHandler, // => confirmed is importing the right function
} from '@middleware';
import routes from '@routes';
import { Logger } from '@utils';
import config from '@config';

const logger = new Logger().context('startup');

async function onAppReady(...args) {
    logger.success(`API listening on port ${config.port}`);
}

express()
    .use(body.json())
    .use(cookies())
    .use(provideLogger)
    .use(responseStructure)
    .use(routes)
    .use(errorHandler) // => applied after routes
    .listen(config.port, onAppReady);

// 路由.js

import { Router } from 'express';
import myRoute from './myRoute';

const router = new Router();

router.use('/route', myRoute);


export default router;

// myRoute.js

import { Router } from 'express';
import endpoint from './endpoint';

const myRoute = new Router();

myRoute.post('/:objectId/', endpoint);


export default myRoute;

// 端点

export default function endpoint(req, res, next) {
  console.log('I am an endpoint, time to trigger an error');
  next({ status: 404, message: 'Success not found :(' });
}

// 中间件

export function errorHandler(
  {
    error = {},
    message = 'An error occurred.',
    status = 500,
  } = {},
  req,
  res,
  next,
) {
  console.log('I am handling the error');
  res.status(status).send({ error: true });
}

当我向端点发送请求时,它会从我的端点打印日志,然后返回一个 HTML 文件,其中包含我传递给 next 的数据作为 HTML 正文。我的 errorHandler 的日志永远不会被打印出来。

我已经翻阅了文档,据我所知,我做的一切都是正确的。我必须错过一些东西,但是什么?为什么我的错误处理程序永远不会被调用??

【问题讨论】:

    标签: node.js express error-handling middleware


    【解决方案1】:

    看起来这是我在错误处理程序中为第一个参数设置默认值的方式的问题。

    改变

    export function errorHandler(
      {
        error = {},
        message = 'An error occurred.',
        status = 500,
      } = {},
      ...
    

    export function errorHandler(
      {
        error = {},
        message = 'An error occurred.',
        status = 500,
      },
      ...
    

    修复它。

    【讨论】:

      【解决方案2】:

      请注意,如果您对引发错误的端点使用异步处理程序,例如

      app.get('/uri', async (req, res) => {
        throw new Error('dummy error');
      });
      

      你应该使用express-async-errors

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多