快速错误处理无法正常工作

时间:2021-01-30 12:30:05

标签: express

我已经尝试了所有处理错误的方法,但从未调用过错误处理中间件。

我尝试了很多方法来处理错误,但似乎当我抛出错误时代码会立即中断。

-- App.js --
const app = express();
app.set('trust proxy', true); 
app.use(json());

app.use(
  cookieSession({
    signed: false, 
    secure: process.env.NODE_ENV !== 'test',
  })
);

// routes
app.use(CurrentUserRoute);
app.use(SignInRoute);
app.use(SignUpRoute);
app.use(SignOutRoute);

app.all('*', async (req, res) => {
  console.log('This is a global error handler at route level....');
  throw new Error('Error');
});

app.use(errorHandler);  // this is the error middleware

错误处理中间件:

import { Request, Response, NextFunction } from 'express';

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  console.log('Something went wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!: ', err);

  res.status(400).send({
    message: 'Something Went Wrong',
  });
};

在我的路由中,每当我抛出错误时,中间件都不会被调用,它会立即显示自己的错误,如

<块引用>

[auth] 错误:“email”长度必须至少为 5 个字符
[身份验证] 在 /app/src/routes/signUp.ts:17:11
[auth] 在步骤 (/app/src/routes/signUp.ts:33:23)
[auth] 在 Object.next (/app/src/routes/signUp.ts:14:53)
[身份验证] 在 /app/src/routes/signUp.ts:8:71
[auth] at new Promise()
[auth] 在 __awaiter (/app/src/routes/signUp.ts:4:12)
[身份验证] 在 /app/src/routes/signUp.ts:11:68
[auth] at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
[auth] 在下一个 (/app/node_modules/express/lib/router/route.js:137:13)
[auth] 在 Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
[auth] at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
[身份验证] 在 /app/node_modules/express/lib/router/index.js:281:22
[auth] 在 Function.process_params (/app/node_modules/express/lib/router/index.js:335:12)
[auth] 在下一个 (/app/node_modules/express/lib/router/index.js:275:10)
[auth] 在 Function.handle (/app/node_modules/express/lib/router/index.js:174:3)
[auth] 在路由器 (/app/node_modules/express/lib/router/index.js:47:12)
[auth] [ERROR] 12:13:25 错误:“email”长度必须至少为 5 个字符

P.S 我将 Docker 和 Kubernetes 环境与 ingress-nginx 服务一起使用,但我认为它在错误处理方面不会有任何问题。

2 个答案:

答案 0 :(得分:0)

解决此问题的方法之一是直接在 app.js 文件中制作中间件。 所以而不是这个:

app.use(errorHandler);

使用这个:

app.use(async (error, req, res, next)=>{

     res.status(400).send({
          message: 'Something Went Wrong',
     });

});

答案 1 :(得分:0)

如果错误处理中间件没有任何错误,您可以在控制器中像这样使用

在错误中间件应该运行后使用 return next()

const MyFunction = async (req, res, next) => {
    const error = new Error("Error Message in controller")
    return next(error);
}

我的错误中间件处理(errorMiddleware.js)

const errorHandler = (err, req, res, next) => {
  console.log("Something went wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!: ", err);

  res.status(400).send({
    message: "Something Went Wrong",
  });
};

exports.errorHandler = errorHandler

在 app.js 中

const {errorHandler} = require('./errorMiddleware');
app.use(errorHandler);