简体   繁体   中英

Error handling in an inversify controller

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?

If you want to re-throw, you can throw whatever you want because commonly the rejected value is not properly typed (ie 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 User | null would be better if you cannot reject, then you can return null in the failure case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM