NestJs 如何抛出错误,避免程序奔溃

63 阅读1分钟
import { BadRequestException, Injectable } from '@nestjs/common';
import { spawn } from 'child_process';

@Injectable()
export class AppService {
  getHelloTest() {
    // 可以直接抛出错误
    // throw new Error('Method not implemented.');
    // throw new BadRequestException('Method not implemented.');
    const childProcess = spawn('ping', ['-c', '2', 'www.baidu.com']);
    childProcess.stdout.on('data', (data: Buffer) => {
      console.log(data.toString());
    });
    childProcess.stderr.on('data', (data: Buffer) => {
      console.log(data.toString());
    });
    return new Promise((resolve, reject) => {
      childProcess.on('close', (code: number) => {
        // resolve(code);
        // throw new Error(`ping 结束,退出码 ${code}`);  // 会直接导致程序退出,触发 uncaughtException 事件
        // throw new BadRequestException(`ping 结束,退出码 ${code}`); // 会直接导致程序退出,触发 uncaughtException 事件
        // Promise.reject(new Error(`ping 结束,退出码 ${code}`));  // 会导致程序退出,会触发 unhandledRejection 事件
        // reject(new Error(`ping 结束,退出码 ${code}`));  // 会被捕获,500 错误
        reject(new BadRequestException(`ping 结束,退出码 ${code}`)); // 会被捕获,400 错误
        // resolve(new BadRequestException(`ping 结束,退出码 ${code}`));
      });
    });
  }
}

// 监听异常
process.on('uncaughtException', (err) => {
  console.log('未捕获的异常', err);
});

// 监听未处理的拒绝,比如 Promise 的 reject 没有被捕获
process.on(' ', (err) => {
  console.log('未处理的拒绝', err);
});