Skip to content
This repository has been archived by the owner on Nov 14, 2019. It is now read-only.

Commit

Permalink
better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
antho1404 committed Aug 21, 2019
1 parent 3773b9a commit 7cb8482
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 20 deletions.
14 changes: 2 additions & 12 deletions src/commands/service/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {flags} from '@oclif/command'
import {InstanceCreateOutputs} from 'mesg-js/lib/api'

import Command from '../../root-command'
import {isAlreadyExists, resourceHash} from '../../utils/error'
import {errorConversion} from '../../utils/error'
import serviceResolver from '../../utils/service-resolver'

export default class ServiceStart extends Command {
Expand Down Expand Up @@ -35,17 +35,7 @@ export default class ServiceStart extends Command {
this.spinner.stop(instance.hash)
return instance
} catch (err) {
return this.handleError(err)
throw errorConversion(err)
}
}

handleError(err: Error) {
if (isAlreadyExists(err, 'instance')) {
const hash = resourceHash(err, 'instance')
this.warn(`instance ${hash} already started`)
this.spinner.stop(hash)
return {hash}
}
throw err
}
}
29 changes: 21 additions & 8 deletions src/utils/error.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
export const isAlreadyExists = (err: Error, resource: string): boolean => {
const reg = new RegExp(`${resource} \"(.*)\" already exists`)
return reg.test(err.message)
export class IsAlreadyExistsError extends Error {
static ID = 'ALREADY_EXISTS'
static regexp = new RegExp('\"(.*)\" already exists')
static match(err: Error) {
return IsAlreadyExistsError.regexp.test(err.message)
}

hash: string

constructor(error: Error) {
super(error.message)
const res = IsAlreadyExistsError.regexp.exec(error.message)
const hash = res && res.length >= 1 ? res[1] : ''
this.hash = hash
this.name = IsAlreadyExistsError.ID
}
}

export const resourceHash = (err: Error, resource: string): string => {
const reg = new RegExp(`${resource} \"(.*)\" already exists`)
const res = reg.exec(err.message)
if (!res) return ''
return res[1]
export const errorConversion = (err: Error): Error => {
if (IsAlreadyExistsError.match(err)) {
return new IsAlreadyExistsError(err)
}
return err
}

0 comments on commit 7cb8482

Please sign in to comment.