简体   繁体   English

Node.js 和 typescript; 如何捕捉表达错误

[英]Node js with typescript; How to catch express errors

So if I am using node.js with javascript, I used to catch errors by adding the following code in my app.js startup file:因此,如果我将 node.js 与 javascript 一起使用,我过去常常通过在我的 app.js 启动文件中添加以下代码来捕获错误:

app.use((req, res, next) => {   next(createError.NotFound()); });

app.use((err, req, res, next) => {
  res.status(err.status || 500).json({
    status: err.status || 500,
    success: 0,
    message: 'Error',
    error: [err.message],
    data: {}
  });
});

the "err" will be automatically caught and it will return for example 404 if I am using a route that does not exist or 500 if the database connection is not established correctly and so on. “错误”将被自动捕获,如果我使用的路由不存在,它将返回例如 404,如果数据库连接未正确建立,则返回 500 等等。

But in typescript, how can I do the same logic?但是在typescript中,我该如何做同样的逻辑呢?

My app.ts file is as follows我的app.ts文件如下

import express, { Application, Request, Response, NextFunction } from 'express';
    import routes from './start/routes';
    
    const app: Application = express();
    app.use('/', require('./routes/api.route'));
    
    app.use(express.json());
    app.use('/api', routes);
    
app.use((err, req: Request, res: Response, next: NextFunction ) => {
    res.status(err.status || 500).json({
        status: err.status || 500,
        success: 0,
        message: 'Error',
        error: [err.message],
        data: {}
    });
});
    
    const PORT = process.env.PORT || 3001;
    app.listen(PORT, () => console.log(`🚀 @ http://localhost:${PORT}`));

this is not compiling.这不是编译。 It says that err.status and err.message are not found.它说找不到 err.status 和 err.message。 What to do?该怎么办?

You are missing the type for the err parameter, which should be any according to the ErrorRequestHandler type.您缺少err参数的类型,根据ErrorRequestHandler类型,它应该是any ErrorRequestHandler 类型

This will make your code compile, and the handler will run automatically when an error occurs.这将使您的代码编译,并且处理程序将在发生错误时自动运行。

To make a default response to 404 though.不过要对 404 做出默认响应。 You will need to add another handler since it's not an error.您将需要添加另一个处理程序,因为这不是错误。

 app.use((req: Request, res: Response, next: NextFunction ) => { 
    // Handle not found
})

NOTE This handler should be last since it accepts every request.注意这个处理程序应该是最后一个,因为它接受每个请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM