@@ -6,6 +6,7 @@ import {Middleware} from "../../src/decorator/Middleware";
6
6
import { UseAfter } from "../../src/decorator/UseAfter" ;
7
7
import { ExpressErrorMiddlewareInterface } from "../../src/driver/express/ExpressErrorMiddlewareInterface" ;
8
8
import { NotFoundError } from "../../src/http-error/NotFoundError" ;
9
+ import { HttpError } from "../../src/http-error/HttpError" ;
9
10
const chakram = require ( "chakram" ) ;
10
11
const expect = chakram . expect ;
11
12
@@ -54,6 +55,25 @@ describe("express error handling", () => {
54
55
55
56
}
56
57
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
+
57
77
@JsonController ( )
58
78
class ExpressErrorHandlerController {
59
79
@@ -97,6 +117,11 @@ describe("express error handling", () => {
97
117
return "1234" ;
98
118
}
99
119
120
+ @Get ( "/stories" )
121
+ stories ( ) {
122
+ throw new ToJsonError ( 503 , "sorry, try it again later" , "impatient user" ) ;
123
+ }
124
+
100
125
}
101
126
} ) ;
102
127
@@ -154,4 +179,15 @@ describe("express error handling", () => {
154
179
} ) ;
155
180
} ) ;
156
181
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
+
157
193
} ) ;
0 commit comments