异常处理
局部异常处理
同步代码异常
try{}
catch(e){}
异步 Promise 代码异常
Promise.reject().then((e)=>{
})
全局异常处理
process
process.on('uncaughtException',(err)=>{
})
process.on(`unhandledRejection`,(err)=>{
})
Koa
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
}
});
Express
```javascript
app.use((err, req, res, next) => {
// logic
})
Nest.js
TODO: New chapter in detail
// http-exception.filter.ts
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
// single route handler
@Post()
@UseFilters(new HttpExceptionFilter())
async create(@Body() createCatDto: CreateCatDto) {
throw new ForbiddenException();
}
// every router in controller
@UseFilters(new HttpExceptionFilter())
export class CatsController {}
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter());
注:
1. unhandledRejection: 每当 Promise 被拒绝并且在事件循环的一个轮询内没有错误句柄附加到承诺时,则会触发 'unhandledRejection' 事件。link
2. 在 .then(()=>{...}) 或者类似段落中出现的Excpetion且未处理可通过unhandledRejection捕获
3. 在新版本的Nodejs中(15+) Rejection 将会导致程序终止