Skip to content

Commit

Permalink
feat(cli): better exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 18, 2020
1 parent c5c4283 commit 34ebc6e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 25 deletions.
18 changes: 1 addition & 17 deletions packages/koishi-cli/src/run.ts
Expand Up @@ -15,25 +15,9 @@ function createWorker (options: WorkerOptions) {
const child = fork(resolve(__dirname, 'worker'), [], {
execArgv: options['--'],
})
let started = false

child.on('message', (data: any) => {
if (data.type === 'start') {
started = true
}
})

child.on('exit', (code) => {
if (!started) process.exit(1)
if (!code) {
logger.info('bot was stopped manually.')
process.exit(0)
}
if (code === 1) {
logger.info('bot was restarted manually.')
} else {
logger.warn('an error was encounted. restarting...')
}
if (code >= 0) process.exit(code)
createWorker(options)
})
}
Expand Down
16 changes: 8 additions & 8 deletions packages/koishi-cli/src/worker.ts
Expand Up @@ -4,7 +4,7 @@ import { capitalize } from 'koishi-utils'
import { performance } from 'perf_hooks'
import { cyan } from 'kleur'
import { logger } from './utils'
import { format } from 'util'
import { format, types } from 'util'
import { readFileSync } from 'fs'
import { safeLoad } from 'js-yaml'
import { yellow } from 'kleur'
Expand All @@ -16,10 +16,13 @@ if (process.env.KOISHI_LOG_LEVEL !== undefined) {
baseLogLevel = +process.env.KOISHI_LOG_LEVEL
}

process.on('uncaughtException', ({ message }) => {
function handleException (error: any) {
const message = types.isNativeError(error) ? error.stack : String(error)
logger.error(message, baseLogLevel)
process.exit(-1)
})
process.exit(1)
}

process.on('uncaughtException', handleException)

const cwd = process.cwd()

Expand Down Expand Up @@ -144,7 +147,4 @@ appList.forEach((app) => {
})
})

startAll().catch((error) => {
logger.error(error, baseLogLevel)
process.exit(-1)
})
startAll().catch(handleException)

0 comments on commit 34ebc6e

Please sign in to comment.