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

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

好吧,我已经使用 javascript 来构建我的 API 很长时间了,我决定开始使用 typescript,正如你可以想象的那样,我不断遇到错误。我有一个自定义错误处理程序,用于在未找到路线时处理,如下所示。

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}`)
})

只要我导入'express-async-errors',上面的代码就可以在javascript中工作,但是在打字稿中我不断收到此错误:

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 asynchronous error-handling
1个回答
0
投票

您应该使用以下命令导入

notFoundErrorHandler

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

express-异步错误

并且

@types/express-async-errors
不存在 - 但
express-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');
}

index.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((req: Request, res: Response) => {
//   res.status(404).send('Route does not exist');
// });
app.use(notFoundHandler);

app.listen(PORT, () => {
  console.log(`app is listening on port ${PORT}`);
});
© www.soinside.com 2019 - 2024. All rights reserved.