当前位置: 首页 > news >正文

nodejs 错误处理

//导入模块
const express = require(‘express’);
//创建应用
const app = express();
app.get(‘/’,(req,resp)=>{
if (!req.query.name) {
throw new Error(“缺少name参数”);
}
resp.end(‘ok’);
});

app.listen(8080,()=>{
console.log(‘listening on 8080’);
});

异步错误处理: 发生在异步调用过程中,通过next(err) 才能捕获异常信息

//导入模块
const express = require('express');
const fs = require('fs');
//创建应用
const app = express();
app.get('/',(req,resp,next)=>{fs.readFile('', { encoding: 'utf8' }, (error,data) => { if (error) { next(error);  //异步错误处理return;}resp.end(data);});resp.end('ok');
});app.listen(8080,()=>{console.log('listening on 8080');
});

自定义错误处理函数

//导入模块
const { error } = require('console');
const express = require('express');
const fs = require('fs');
//创建应用
const app = express();app.get('/',(req,resp,next)=>{throw new Error("发生错误");
});app.use((error, req, resp, next) => { resp.json({path: req.path,message: error.message});
});app.listen(8080,()=>{console.log('listening on 8080');
});

多个错误处理函数

//导入模块
const { error } = require('console');
const express = require('express');
const fs = require('fs');
//创建应用
const app = express();app.get('/',(req,resp,next)=>{throw new Error("发生错误");
});app.get('/',(req,resp,next)=>{fs.readFile('', { encoding: 'utf8' }, (error,data) => { if (error) { next(error);  //异步错误处理return;}resp.end(data);});resp.end('ok');
});
app.use((error, req, resp, next) => { resp.json({path: req.path,message: error.message});
});app.listen(8080,()=>{console.log('listening on 8080');
});
http://www.lryc.cn/news/623941.html

相关文章:

  • Collections.synchronizedList是如何将List变为线程安全的
  • vs studio 2017项目不支持studio vs2022
  • 【k8s】Kubernetes核心概念与架构详解
  • 从0实现系统设计
  • Leetcode 15 java
  • GitHub Copilot:AI编程助手的架构演进与真实世界影响
  • 浜掕仈缃戝ぇ鍘侸ava姹傝亴鑰呴潰璇曠幇鍦猴細褰撲弗鑲冮潰璇曞畼閬囦笂鎼炵瑧绋嬪簭鍛樿阿椋炴満
  • Conda 环境 在AI 私有化部署 有怎么用?
  • 电力设备状态监测与健康管理:基于多源异构数据融合的技术实现
  • 五、redis入门 之 客户端连接redis
  • 计算机网络 HTTP1.1、HTTP2、HTTP3 的核心对比及性能分析
  • ReactNode 类型
  • Java项目中短信的发送
  • 密码学系列 - 零知识证明(ZKP) - 多种承诺方案
  • Java ConcurrentHashMap 深度解析
  • 【LeetCode 热题 100】(八)二叉树
  • EC11编码器
  • 集成电路学习:什么是SIFT尺度不变特征变换
  • 43 C++ STL模板库12-容器4-容器适配器-堆栈(stack)
  • 基于DSP+ARM+FPGA架构的储能协调控制器解决方案,支持全国产化
  • 电子电气架构 --- 自动驾驶汽车的下一步发展是什么?
  • 下降路径最小和
  • 【网络通信】TCP/IP 协议全方位解析​
  • java如何把字符串数字转换成数字类型
  • OpenCV 图像处理核心技术:边界填充、算术运算与滤波处理实战
  • android aidl相关学习
  • 常用的SQL语句
  • java16学习笔记
  • topographic terrain
  • AMBA-AXI and ACE协议详解(七)