Express-js 错误处理程序未能返回预期的错误

问题描述 投票:0回答:1

我正在使用mongoose与db交互,使用errorHandler中间件来处理异常error

控制器:

const asyncHandler = require('express-async-handler');
const Contact = require('../models/contactModel');

const getContact = asyncHandler(async (req, res) => {
  const contact = await Contact.findById(req.params.id);

  if (!contact) {
    res.status(404);
    throw new Error('Contact not found');
  }

  res.status(200).json(contact);
});

errorHandler 中间件:

const { constants } = require('../constants');
const errorHandler = (err, req, res, next) => {
  const statusCode = res.statusCode ? res.statusCode : 500;

  switch (statusCode) {
    case constants.VALIDATION_ERROR:
      res.json({
        title: 'Validation failed',
        message: err.message,
        stackTrace: err.stack
      });
    case constants.UNAUTHORIZED:
      res.json({
        title: 'Unauthorized',
        message: err.message,
        stackTrace: err.stack
      });
    case constants.FORBIDDEN:
      res.json({
        title: 'Forbidden',
        message: err.message,
        stackTrace: err.stack
      });
    case constants.NOT_FOUND:
      res.json({
        title: 'Not found',
        message: err.message,
        stackTrace: err.stack
      });
    case constants.SERVER_ERROR:
      res.json({
        title: 'Server error',
        message: err.message,
        stackTrace: err.stack
      });
    default:
      console.log('No error, all is well !');
      break;
  }
};

它工作正常如果找到文件, 但是如果它没有得到结果,错误处理程序中间件似乎总是得到默认的 switch case 而不是返回 404 错误,

我怎么解决这个问题?

node.js express mongoose error-handling middleware
1个回答
0
投票

您没有

break
case
子句,因此它“落空”到
default
子句。见Breaking and fall-through

应该是:

switch (statusCode) {
  case constants.NOT_FOUND:
    res.json({
      title: 'Not found',
      message: err.message,
      stackTrace: err.stack
    });
    // don't forget 
    break;
  default:
    console.log('No error, all is well !');
    break;
}
© www.soinside.com 2019 - 2024. All rights reserved.