From daa82278332d7617d6ebb3d07e8cdfd1e95cf644 Mon Sep 17 00:00:00 2001 From: Eward Song Date: Mon, 26 Jun 2017 21:54:45 +0800 Subject: [PATCH] feat(tsd): add ctx.logger and logger.error support Error object (#1108) --- index.d.ts | 11 ++++++++++- test/fixtures/apps/app-ts/app/controller/foo.ts | 15 ++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/index.d.ts b/index.d.ts index 71ea4b910a..eba965d946 100644 --- a/index.d.ts +++ b/index.d.ts @@ -35,9 +35,11 @@ export interface Logger { info(info: string, ...args: string[]): void; warn(info: string, ...args: string[]): void; debug(info: string, ...args: string[]): void; - error(info: string, ...args: string[]): void; + error(info: string | Error, ...args: string[]): void; } +export type RequestArrayBody = any[]; +export type RequestObjectBody = { [key: string]: any }; interface Request extends KoaApplication.Request { // tslint:disable-line /** * detect if response should be json @@ -116,6 +118,8 @@ interface Request extends KoaApplication.Request { // tslint:disable-line * ``` */ query: { [key: string]: string }; + + body: RequestArrayBody | RequestObjectBody; } interface Response extends KoaApplication.Response { // tslint:disable-line @@ -724,6 +728,11 @@ export interface Context extends KoaApplication.Context { */ curl(url: string, opt: any): Promise; + /** + * Get logger by name, it's equal to app.loggers['name'], but you can extend it with your own logical + */ + getLogger(name: string): Logger; + /** * Render a file by view engine * @param {String} name - the file path based on root diff --git a/test/fixtures/apps/app-ts/app/controller/foo.ts b/test/fixtures/apps/app-ts/app/controller/foo.ts index f9da879ccc..ba5aefbd42 100644 --- a/test/fixtures/apps/app-ts/app/controller/foo.ts +++ b/test/fixtures/apps/app-ts/app/controller/foo.ts @@ -1,4 +1,4 @@ -import { Controller } from 'egg'; +import { Controller, RequestObjectBody } from 'egg'; // add user controller and service declare module 'egg' { @@ -10,9 +10,18 @@ declare module 'egg' { // controller export default class FooController extends Controller { async getData() { - this.ctx.body = await this.ctx.service.foo.bar(); + try { + this.ctx.body = await this.ctx.service.foo.bar(); + } catch (e) { + const body: RequestObjectBody = this.ctx.request.body; + this.app.logger.info(e.name, body.foo); + } } async getBar() { - this.ctx.body = await this.service.foo.bar(); + try { + this.ctx.body = await this.service.foo.bar(); + } catch (e) { + this.ctx.logger.error(e); + } } }