@@ -8,39 +8,57 @@ You can get the latest release using npm:
88$ npm install --save ts-httpexceptions
99```
1010
11- > ** Important!** Ts.ED requires Node >= 6, Express >= 4 and TypeScript >= 2.0.
11+ > ** Important!** Ts.ED requires Node >= 8 and TypeScript >= 2.0.
1212
1313
1414## Example
1515
1616``` typescript
17- import {BadRequest , Exception } from ' ts-httpexceptions' ;
18- let express = require (' express' );
19- let app = express ();
20-
21- app .get (' /my/route' , (req , res ) => {
17+ import {BadRequest , Exception , NotFound } from ' ts-httpexceptions' ;
18+ const express = require (' express' ); // Koa works also
19+ const app = express ();
20+
21+ app .get (' /my/route/:id' , async (req , res , next ) => {
22+ if (req .params .id === undefined ) {
23+ const error = new BadRequest (" ID is required" )
2224
23- throw new BadRequest (' Custom Message' ); // Emit
24- // OR
25- // throw new Exception(510, 'Custom Message');
25+ // Additionally
26+ error .headers = {
27+ ' x-header' : ' value'
28+ }
29+ error .errors = [{' message' : " ID is required" }]
30+ error .body = [{' message' : " ID is required" }]
2631
27- });
32+ next (error );
33+ }
34+
35+ try {
36+ const user = await getUser (res .params .id )
37+ res .json (user );
38+ } catch (origin ) {
39+ next (new NotFound (' User not found' , origin ))
40+ }
41+ });
42+
43+
44+ // GlobalHandler middleware catch exception and send response to the client
45+ app .use ((err , request , response , next ) => {
46+ if (err instanceof Exception ) {
47+ if (err .errors ) { // If errors is provided
48+ response .set ({' x-errors' : JSON .stringify (err .errors )})
49+ }
2850
29- app .get (' /my/route/params' , (req , res ) => {
30-
31- if (req .params .id === undefined ){
32- throw new BadRequest ();
33- }
34-
35- });
51+ if (err .headers ) {
52+ response .set (err .headers )
53+ }
3654
55+ if (err .body ) { // If a body is provided
56+ return response .status (err .status ).json (err .body )
57+ }
3758
38- // GlobalHandler middleware catch exception and send response to the client
39- app .use ((err , request , response ) => {
40-
41- if (err instanceof Exception ){
42- response .status (err .status ).send (err .message );
43- }
44-
45- });
59+ return response .status (err .status ).send (err .message );
60+ }
61+
62+ next ()
63+ });
4664```
0 commit comments