javascript - 在 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
,这将被handleError
中间件捕获,但该.json(err)
部分将只显示{}
有没有办法我可以使用相同的中间件同时获取服务器错误(正常工作)和内部服务器错误?
解决方案
你可以扩展toJSON
Error的方法。
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
参数的方法。您可以在Is it possible to stringify an Error using JSON.stringify 中阅读更多内容?
.
但是,我建议只在方法中公开“消息”属性toJSON
。
推荐阅读
- java - 使用存储过程从输入 csv 文件将多个表创建到 oracle 数据库中
- javascript - 如何存储每个 Http 请求的变量
- android - Android Jetpack 递归导航
- mysql - 将 JMeter 的结果发送到 MySql DB
- ios - 在核心数据中保存新实体时如何创建非可选实体?
- r - R Studio:抓取表格时下标越界
- python - 如何从字符串中提取小时并填充空字典?
- javascript - 用自定义 URL 替换表单操作
- jasper-reports - jasper 报告在动态内容表下方显示静态文本
- sql - 他们购买的第一个产品,他们购买的下一个产品将是第一个产品的子产品