Skip to content

Commit

Permalink
feat(core): provide default global exception handlers and the ability…
Browse files Browse the repository at this point in the history
… to replace them with custom exception handlers
  • Loading branch information
zhengjianhui committed Apr 12, 2023
1 parent 45fded6 commit f3225cc
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 40 deletions.
12 changes: 2 additions & 10 deletions packages/io/__tests__/cor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,28 +105,20 @@ describe('Test CoR', () => {
})

it(`should call error handler`, async () => {
const err = new Error('this is error')
const httpErr = new NotFound()
const kuaiErr = new KuaiError({
code: 'test',
message: 'this is http error',
})

let cor = CoR.defaultCoR()
cor.use(async (_ctx, _next) => {
throw err
})

await expect(cor.dispatch({})).rejects.toThrow(`UNKNOWN ERROR`)

cor = CoR.defaultCoR()
let cor = new CoR()
cor.use(async (_ctx, _next) => {
throw httpErr
})

await expect(cor.dispatch({})).rejects.toThrow(`Not Found`)

cor = CoR.defaultCoR()
cor = new CoR()
cor.use(async (_ctx, _next) => {
throw kuaiErr
})
Expand Down
30 changes: 8 additions & 22 deletions packages/io/src/cor.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
import { CoR as ICoR, Middleware, Context, JsonValue } from './types'
import compose from 'koa-compose'
import { isHttpError } from 'http-errors'
import { KuaiError } from '@ckb-js/kuai-common'

export const UNKNOWN = {
UNKNOWN_ERROR: {
code: 'UNKNOWN ERROR',
message: 'UNKNOWN ERROR',
},
}

export class CoR<ContextT extends object = Record<string, never>> implements ICoR<ContextT> {
private _exceptionHandler: Middleware<ContextT> = CoR.handleException()
private _middlewares: Middleware<ContextT>[] = []

public use<NewContext = unknown>(plugin: Middleware<NewContext & ContextT>): CoR<NewContext & ContextT> {
this._middlewares = [...this._middlewares, plugin] as Middleware<ContextT>[]
return this
}

public useExceptionHandler(plugin: unknown): CoR<ContextT> {
this._exceptionHandler = plugin as Middleware<ContextT>
return this
}

public async dispatch<Ok, Payload extends JsonValue>(payload: Payload): Promise<Ok | void> {
return new Promise((resolve, rej) => {
const ctx: Context<ContextT> = {
Expand All @@ -26,27 +23,16 @@ export class CoR<ContextT extends object = Record<string, never>> implements ICo
err: rej,
} as Context<ContextT>

compose(this._middlewares)(ctx)
compose([this._exceptionHandler, ...this._middlewares])(ctx)
})
}

public static defaultCoR(): CoR {
const cor = new CoR()
cor.use(CoR.handleException())

return cor
}

private static handleException(): Middleware {
return async (context, next) => {
try {
await next()
} catch (e) {
if (e instanceof KuaiError || isHttpError(e)) {
context.err(e)
} else {
context.err(new KuaiError(UNKNOWN.UNKNOWN_ERROR, e as Error))
}
context.err(e)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/samples/mvp-dapp/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { router } from '../src/app.controller'

describe('controller test', () => {
test('/load', async () => {
const cor = CoR.defaultCoR()
const cor = new CoR()
cor.use(router.middleware())

await expect(cor.dispatch({ method: 'GET', path: '/load/mistakeaddress' })).rejects.toThrow('invalid address')
Expand Down
8 changes: 3 additions & 5 deletions packages/samples/mvp-dapp/src/exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,12 @@ export function handleException() {
await next()
} catch (err) {
if (isHttpError(err)) {
ctx.body = { message: err.message }
ctx.status = err.status
ctx.err(err)
} else if (err instanceof MvpError) {
ctx.status = 200
ctx.body = MvpResponse.err(err.message, err.code)
ctx.ok(MvpResponse.err(err.message, err.code))
} else {
ctx.status = 500
ctx.body = { message: 'Internal server error' }
ctx.err(new Error('Internal server error'))
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/samples/mvp-dapp/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,12 @@ async function bootstrap() {
app.use(koaBody())

// init kuai io
const cor = CoR.defaultCoR()
const cor = new CoR()
cor.use(router.middleware())
cor.useExceptionHandler(handleException())

const koaRouterAdapter = new KoaRouterAdapter(cor)

app.use(handleException())
app.use(cors())
app.use(koaRouterAdapter.routes())

Expand Down

0 comments on commit f3225cc

Please sign in to comment.