0

I'm using the inversify-express-utils package.

Suppose I have a controller action that returns a User entity:

  @httpGet("/:id")
  public async getUser(): Promise<User> {
    try {
      const id = this.httpContext.request.params.id;
      return await this._userRepository.get(id);
    }
    catch (e) {
      this.httpContext.response.status(404);
      // ...what goes here?
    }
  }

I know I can omit the return type, but I don't want to circumvent the type system.

So what do I return from that catch block?

lonix
  • 14,255
  • 23
  • 85
  • 176

1 Answers1

1

If you want to re-throw, you can throw whatever you want because commonly the rejected value is not properly typed (i.e. is any).

lib.es5.d.ts:

interface Promise<T> {
    then<TResult1 = T, TResult2 = never>(
        onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
        // See `reason` below
        onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
    ): Promise<TResult1 | TResult2>;

One might argue that Promise should have two generic type parameters...

If you do catch and return a value it has to be a User object as indicated. Hitting a 404 sounds more like a rejection to me but i am not familiar with that library so if it would not handle a rejection properly you may have to return a value.

Possibly changing the return type to User | null would be better if you cannot reject, then you can return null in the failure case.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Do you mean `return Promise.reject();` ? Will that cause "unhandled rejection" problems? – lonix Mar 05 '19 at 10:57
  • In an `async` function a `throw` will cause a rejection. Whether that causes problems depends on how express & inversify handle rejections in a route handler, which i unfortunately do not know, i only ever used express (and not much at that). – H.B. Mar 05 '19 at 11:38
  • Thanks for your advice! I want to leave this open a while longer in the hope that someone else had this issue. – lonix Mar 05 '19 at 11:42