@@ -6,6 +6,7 @@ import {Middleware} from "../../src/decorator/Middleware";
66import { UseAfter } from "../../src/decorator/UseAfter" ;
77import { ExpressErrorMiddlewareInterface } from "../../src/driver/express/ExpressErrorMiddlewareInterface" ;
88import { NotFoundError } from "../../src/http-error/NotFoundError" ;
9+ import { HttpError } from "../../src/http-error/HttpError" ;
910const chakram = require ( "chakram" ) ;
1011const expect = chakram . expect ;
1112
@@ -54,6 +55,25 @@ describe("express error handling", () => {
5455
5556 }
5657
58+ class ToJsonError extends HttpError {
59+ public publicData : string ;
60+ public secretData : string ;
61+
62+ constructor ( httpCode : number , publicMsg ?: string , privateMsg ?: string ) {
63+ super ( httpCode ) ;
64+ Object . setPrototypeOf ( this , ToJsonError . prototype ) ;
65+ this . publicData = publicMsg || "public" ;
66+ this . secretData = privateMsg || "secret" ;
67+ }
68+
69+ toJSON ( ) {
70+ return {
71+ status : this . httpCode ,
72+ publicData : `${ this . publicData } (${ this . httpCode } )`
73+ }
74+ }
75+ }
76+
5777 @JsonController ( )
5878 class ExpressErrorHandlerController {
5979
@@ -97,6 +117,11 @@ describe("express error handling", () => {
97117 return "1234" ;
98118 }
99119
120+ @Get ( "/stories" )
121+ stories ( ) {
122+ throw new ToJsonError ( 503 , "sorry, try it again later" , "impatient user" ) ;
123+ }
124+
100125 }
101126 } ) ;
102127
@@ -154,4 +179,15 @@ describe("express error handling", () => {
154179 } ) ;
155180 } ) ;
156181
182+ it ( "should process JsonErrors by their toJSON method if it exists" , ( ) => {
183+ return chakram
184+ . get ( "http://127.0.0.1:3001/stories" )
185+ . then ( ( response : any ) => {
186+ expect ( response ) . to . have . status ( 503 ) ;
187+ expect ( response . body ) . to . have . property ( "status" ) . and . equals ( 503 ) ;
188+ expect ( response . body ) . to . have . property ( "publicData" ) . and . equals ( "sorry, try it again later (503)" ) ;
189+ expect ( response . body ) . to . not . have . property ( "secretData" ) ;
190+ } ) ;
191+ } ) ;
192+
157193} ) ;
0 commit comments