当前位置: 首页 > 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.dtcms.com/a/336294.html

相关文章:

  • Shell脚本-条件判断相关参数
  • 任务型Agent架构简介
  • JUC并发编程04 - 同步/syn-ed(01)
  • prototype 和 _ _ proto _ _的关联
  • 计算机网络 OSI 七层模型和 TCP 五层模型
  • 【Linux系列】如何在 Linux 服务器上快速获取公网
  • 遥感数据介绍——MODIS、VIIRS、Sentinel-2
  • 飞算JavaAI结合Redis实现高性能存储:从数据瓶颈到极速读写的实战之旅
  • 三种变量类型在局部与全局作用域的区别
  • 大模型算法岗面试准备经验分享
  • 【Linux网络编程】NAT、代理服务、内网穿透
  • css中 hsl() 的用法
  • Java-I18n
  • 43 C++ STL模板库12-容器4-容器适配器-堆栈(stack)
  • 百度笔试编程题 选数
  • PWM控制LED亮度:用户态驱动开发详解
  • Soundraw - 你的AI音乐生成器
  • 51单片机-驱动静态数码管和动态数码管模块
  • linux线程被中断打断,不会计入调度次数
  • 解决 SECURE_PCI_CONFIG_SPACE_ACCESS_VIOLATION蓝屏报错
  • 攻防世界—unseping(反序列化)
  • 机器学习----PCA降维
  • RocketMQ面试题-未完
  • 芋道RBAC实现介绍
  • python+flask后端开发~项目实战 | 博客问答项目--模块化文件架构的基础搭建
  • Valgrind 并发调试 ·:用 Helgrind 抓住线程里的“看不见的错”
  • 数据结构:在二叉搜索树中插入元素(Insert in a BST)
  • linux-高级IO(上)
  • 猫头虎AI分享|一款Coze、Dify类开源AI应用超级智能体Agent快速构建工具:FastbuildAI
  • #买硬盘欲安装k8s记