NodeJS 自定义错误处理在typescriptexpress?

iq3niunx  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(120)

好吧,我已经使用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}`)
})


上面的代码在JavaScript中工作,只要我导入'express-expressc-errors',但是在typescript中我一直得到这个错误:

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-sourcec-errors ''时,我也得到了一个错误:

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


有没有人能告诉我出了什么问题,如何解决?

2guxujil

2guxujil1#

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

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

字符串

express-tagc-errors

@types/express-async-errors不存在-但是express-async-errors可以处理typescript,如下所述:Not working with typescript

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(notFoundHandler);

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

结果

  • http://localhost:3000/hi

/hi

  • http://localhost:3000/

Route does not exist

相关问题