处理express中的javascript错误



假设我有以下异步函数

export async function someAsyncFunction() {
const result = await fetchData();
return result[0].id;
}

在路线上我有

router.post(
'/some-path',
handleErrorAsync(async (req: Request, resp: Response, _err: Errback) => {
const data = await someAsyncFunction();
resp.json(data)
})
);

我有做的错误处理功能

interface ResponseError extends Error {
statusCode: number;
}
// Middleware to respond with an error when error caught
export function handleError(
err: ResponseError,
_req: Request,
resp: Response,
_next: NextFunction
) {
if (err) {
resp.status(err.statusCode || 500).json(err);
}
}
export const handleErrorAsync = (func: Function) => (
req: Request,
res: Response,
next: NextFunction
) => {
func(req, res, next).catch((error: Error) => {
next(error);
});
};

因此,如果例如fetchData有一个错误响应对象,但当错误是一个常规的javascript错误时,它无法打印错误对象,而是只打印带有500错误的{}

例如,在这行return result[0].id;中,如果结果为空([](,那么这将抛出TypeError,CCD_5将被handleError中间件捕获,但.json(err)部分将仅显示{}

有没有一种方法可以用同一个中间件同时获得服务器错误(正常工作(和内部服务器错误?

res.json do json.parse,返回一个空对象{}

我可以建议销毁错误体。

resp.status(err.statusCode || 500).json({message:err.message, error:err});

这将为每个本机错误提供一条消息

您可以扩展Error的toJSON方法。

let a = new Error("hi")
console.log(JSON.stringify(a))
Error.prototype.toJSON = function () {
const alt = {};
// get all property
Object.getOwnPropertyNames(this).forEach((key) => {
alt[key] = this[key];
});
// only get message property
// alt["message"] = this["message"]
return alt;
}
console.log(JSON.stringify(a))

然后只需调用res.json(error),就会得到Error的属性
因为当您调用res.json(parameter)时,express会触发参数的toJSON方法。您可以在使用JSON.stringify字符串化错误吗?。
但是,我建议只暴露"消息";属性。

我建议在这样的错误处理程序中使用res.send((

return res.status(500).send(err.message);

我使用https://www.npmjs.com/package/serialize-error

import { serializeError } from 'serialize-error';
if (err) {
resp
.status(err.statusCode || 500)
.json(serializeError(err));
}

最新更新