TypeScript Express 中的自定义错误处理?

custom error handling in typescript express?

提问人:gerard 提问时间:11/13/2023 最后编辑:gerard 更新时间:11/14/2023 访问量:58

问:

好的,所以我长期以来一直在使用 javascript 来构建我的 API,我决定开始使用打字稿,正如您可以想象的那样,我不断遇到错误。我有一个自定义错误处理程序,用于在找不到路由时,如下所示。

import express, {Response, Request } from 'express'
const notFoundErrorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => res.status(404).send('Route does not exist')

export = notFoundErrorHandler

那么这就是我的app.ts的样子:

import express from 'express'
import 'express-async-errors';
const app = express()

import notFoundErrorHandler = require('./middleware/not-found')

app.use(notFoundErrorHandler);

app.get('/hi', (req, res) => {
    res.send('HIIIIIIII')
})

app.listen(process.env.PORT, () => {
    console.log(`app is listening on port ${process.env.PORT}`)
})

上面的代码在javascript中有效,只要我导入'express-async-errors',但是在打字稿中,我一直收到此错误:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(err: Error, req: Request, res: Response, next: NextFunction)' is not assignable to parameter of type 'PathParams'.

当我尝试在控制台中运行“npm i --save-dev @types/express-async-errors”时,我也收到一个错误:

404 Not Found - GET https://registry.npmjs.org/@types%2fexpress-async-errors - Not found
'@types/express-async-errors@*' is not in this registry.

谁能告诉我出了什么问题以及如何解决它?

Node.js TypeScript Express 异步 错误处理

评论

0赞 gerard 11/13/2023
@eekinci如果您不介意,您介意协助举个例子吗,我调整了代码以匹配(err、req、res、next)类型,但现在的错误基本相同

答:

0赞 eekinci 11/13/2023 #1

您应该使用以下命令导入您的:notFoundErrorHandler

import notFoundErrorHandler from './middleware/not-found'

express-async-errors

并且不存在 - 但适用于打字稿,如下所述: 不使用打字稿 @types/express-async-errorsexpress-async-errors

import "express-async-errors";
// works perfectly fine for me in TS, ,maybe that is your fix?

中间件.ts

import { Request, Response } from 'express';

export function notFoundHandler(req: Request, res: Response) {
  res.status(404).send('Route does not exist');
}

索引.ts

import express, { Request, Response } from 'express';
import 'express-async-errors';
import { notFoundHandler } from './middleware';

const app = express();
const PORT = process.env.PORT || 3000;

app.get('/hi', (req: Request, res: Response) => {
  res.send(req.path);
});

app.use(notFoundHandler);

app.listen(PORT, () => {
  console.log(`app is listening on port ${PORT}`);
});

结果

  • http://localhost:3000/hi

    /hi

  • http://localhost:3000/

    Route does not exist

评论

0赞 gerard 11/14/2023
我真的感谢您的回复,它似乎对您来说工作得很好,但是在复制完全相同的代码后,它仍然会出现错误。我在想,我设置项目的方式一定存在根本性问题。老实说,我别无选择,因为我尝试了一切,我会尝试再次设置项目并重试。再次感谢您的输入。