Tsed: Use promise rejection as output message in controllers

Created on 27 Apr 2017  路  2Comments  路  Source: tsedio/tsed

AFAIK actually the promise rejection is not being user for anything, i notice it because i had to use the response object to set the error manually, but what about if the reject of the promise handles the user response, BTW the status code must have to be set manually but doing what i suggest will allow developers write less code

question

All 2 comments

Hi @jlberrocal,

Yes, I see what you mean. Normally, express set a flag when a response is sent (eg. response.headersSent). The global error handler check that in ts-express-decorators (by default https://github.com/Romakita/ts-express-decorators/wiki/Class:-ServerLoader---Lifecycle-Hooks#serverloaderonerrorerror-request-response-next-void).

But you can override the global error handler and forgot to check this flag. In this case, the first response will be sent and express emit an error for the next response.send() call.

The promise rejection is here to handle all error not managed by the developper. This error will be forwarded to the next express middleware.

To write less code, I suggest you to use a library Exception like ts-httpexceptions (or other ;)). Here an example:

import {NotFound} from "ts-httpsexceptions";

@Controller()
class MyCtrl {
   @Get('/:userid')
   getUser(@PathParam('userid') userid: string) {
       const users = ["1", "4"]
       return new Promise((resolve, reject) => {

           if(users.indexOf(userid) >-1) { 
                 resolve({id: userid, name: "John"});
           } else {
                 reject(new NotFound('user not found'));
           }
       });
  } 
}

This example show you how you can change the status code when the user not found.

HttpException is here => https://www.npmjs.com/package/ts-httpexceptions

You do not have to use the response object ;)

See you,
Romain

got it, thanks for your help @Romakita

Was this page helpful?
0 / 5 - 0 ratings