fix: catch system uncaught exception

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2022-08-28 21:02:50 +08:00
parent ac82a7eab0
commit 90bfc624f3
2 changed files with 46 additions and 3 deletions

View File

@@ -32,6 +32,7 @@ type myError = {
readonly message?: string
}
let once = false
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private readonly logger = new Logger(AllExceptionsFilter.name)
@@ -39,7 +40,38 @@ export class AllExceptionsFilter implements ExceptionFilter {
constructor(
@Inject(REFLECTOR) private reflector: Reflector,
private readonly eventManager: EventManagerService,
) {}
) {
this.registerCatchAllExceptionsHook()
}
registerCatchAllExceptionsHook() {
if (once) {
return
}
process.on('unhandledRejection', (reason) => {
console.error('unhandledRejection: ', reason)
this.eventManager.broadcast(
EventBusEvents.SystemException,
{ message: reason },
{
scope: EventScope.TO_SYSTEM,
},
)
})
process.on('uncaughtException', (err) => {
console.error('uncaughtException: ', err)
this.eventManager.broadcast(
EventBusEvents.SystemException,
{ message: err?.message ?? err, stack: err?.stack },
{
scope: EventScope.TO_SYSTEM,
},
)
})
once = true
}
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp()
const response = ctx.getResponse<FastifyReply>()

View File

@@ -2,10 +2,12 @@
import cluster from 'cluster'
import { render } from 'ejs'
import { createTransport } from 'nodemailer'
import Mail from 'nodemailer/lib/mailer'
import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { BizException } from '~/common/exceptions/biz.exception'
import { EventBusEvents } from '~/constants/event-bus.constant'
import { ConfigsService } from '~/modules/configs/configs.service'
@@ -177,7 +179,7 @@ export class EmailService {
this.logger.log(options)
return
}
await this.instance.sendMail(options)
await this.send(options)
} else {
const options = {
from,
@@ -194,7 +196,7 @@ export class EmailService {
this.logger.log(options)
return
}
await this.instance.sendMail(options)
await this.send(options)
}
}
@@ -225,6 +227,15 @@ export class EmailService {
getInstance() {
return this.instance
}
async send(options: Mail.Options) {
try {
return await this.instance.sendMail(options)
} catch (err) {
this.logger.warn(err.message)
throw new BizException('邮件发送失败')
}
}
}
export interface EmailTemplateRenderProps {