Express 和 Typescript - Error.stack 和 Error.status 属性不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28793098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Express and Typescript - Error.stack and Error.status properties do not exist
提问by Joel
I'm trying to convert an existing node.js project from javascript to typescript. I've been using the default 404 error catcher from the Visual Studio Express 4 template:
我正在尝试将现有的 node.js 项目从 javascript 转换为 typescript。我一直在使用 Visual Studio Express 4 模板中的默认 404 错误捕获器:
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
However, I'm getting the following error message: Property 'status' does not exist on type 'Error'.
但是,我收到以下错误消息: “错误”类型上不存在属性“状态”。
I get a similar message if I try and invoke the Error's .stack property: Property 'stack' does not exist on type 'Error'.
如果我尝试调用错误的 .stack 属性,我会收到类似的消息: “错误”类型上不存在属性“堆栈”。
Does anyone know what's going on here?
有谁知道这里发生了什么?
Edit:Steve Fenton points out that I could just put the error status on the response object. However, my error handling mechanism uses a two-step process:
编辑:Steve Fenton 指出我可以将错误状态放在响应对象上。但是,我的错误处理机制使用了一个两步过程:
- Create the 404 error and set its status
Hand it on to the following generic handler:
app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); });
- 创建 404 错误并设置其状态
将其交给以下通用处理程序:
app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); });
So the error status is first set on the Error object, then read back by the error handler to decide how to handle the error.
所以错误状态首先在 Error 对象上设置,然后由错误处理程序读回以决定如何处理错误。
采纳答案by basarat
You can tell TypeScript that for youruse case Error
might have a status
on it:
您可以告诉 TypeScript,对于您的用例,它Error
可能有一个status
:
interface Error{
status?: number;
}
So you get:
所以你得到:
interface Error{
status?: number;
}
var err = new Error('Not Found');
err.status = 404;
However I have to say that your express code is non-idiomatic, but TypeScript can understand it, if you tell it about it.
但是我不得不说你的 express 代码是非惯用的,但是如果你告诉它,TypeScript 可以理解它。
回答by Fenton
You put the error code on the response...
您将错误代码放在响应中...
app.use(function (req, res, next) {
var err = new Error('Not Found');
res.status(404)
next(err);
});
回答by Reinstate Monica
The best way in my opinion, is not to disable type checks by setting the error to any
, or creating a new Error
type, since one already exists in @types/node
.
在我看来,最好的方法是不要通过将错误设置为any
或创建新Error
类型来禁用类型检查,因为@types/node
.
Instead, you should extend that error type:
相反,您应该扩展该错误类型:
interface ResponseError extends Error {
status?: number;
}
回答by kunl
import * as express from 'express';
interface Error {
status?: number;
message?: string;
}
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
回答by dmwong2268
This is generally a question of how to lazily initialize objects in Typescript.
这通常是一个如何在 Typescript 中延迟初始化对象的问题。
The ideal way to do this is:
执行此操作的理想方法是:
interface ErrorWithStatus extends Error {
status: string
}
let foo = new Error() as ErrorWithStatus;
foo.status = '404';
Using any
, or interfaces with nullable fields, leave you with subpar and weak contracts.
使用any
, 或带有可为空字段的接口,会给您留下低于标准和弱合同。
回答by Manu
Another option in TypeScript:
TypeScript 中的另一个选项:
let err: any;
err = new Error();
err.status = 404;
回答by Matthias
Another option in TypeScript:
TypeScript 中的另一个选项:
const err: { status?: number, message:string } = new Error('Not Found');
err.status = 404;
回答by Rutger de Graaf
If I am not mistaken it is always best to get the type that is actually expected. I couldn't find any hard support that I am right, but I use:
如果我没记错的话,最好得到实际预期的类型。我找不到任何正确的支持,但我使用:
import createError, { HttpError } from 'http-errors';
and to be complete for all types I also import the parameter types of use:
为了完成所有类型,我还导入了使用的参数类型:
import express, { Request, Response, NextFunction } from 'express';
The actual function I use then looks like this:
我使用的实际函数如下所示:
app.use((err: HttpError, req: Request, res: Response, next: NextFunction) => { ... }
In your case if you want to create your own error:
在您的情况下,如果您想创建自己的错误:
app.use((req: Request, res: Response, next: NextFunction) => {
next(createError(404));
});
or closer to your code:
或更接近您的代码:
app.use((req: Request, res: Response, next: NextFunction) => {
let err = new HttpError('Not found');
err.status = 404;
next(err);
});
回答by czechboy
I just went for
我只是去了
var err = new Error('Not Found');
err['status'] = 404;