Dealing with errors in an inversify controller

I am currently utilizing the inversify-express-utils library.

Let's say I have a controller action that is responsible for retrieving 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 should be included here?
    }
  }

I understand that I can exclude the return type, but I prefer not to bypass the type system.

So, what should I include in the catch block?

Answer №1

If you decide to throw again, feel free to throw whatever you prefer because often the rejected value is not correctly typed (e.g. it is any).

lib.es5.d.ts:

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

Some may argue that Promise should have two specific type parameters...

If you do catch and return a value, make sure it is of type User as specified. It seems more like a rejection to encounter a 404 error, but if the library does not handle rejections properly, you may need to return a value.

You might want to consider changing the return type to User | null if rejection is not possible, so you can return null in case of failure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can ES6 class getters, setters, and private properties be utilized in TypeScript with an interface?

I'm currently using TypeScript and trying to figure out how to implement an interface in a class that utilizes ES6 getters and setters. Is it even possible? When I use the code below, errors are highlighted in the class. For instance: (property) S ...

Experimenting with the routerLink directive in Angular 2

Currently, I am in the process of testing routing functionality. As part of this, I have moved my navbar to a separate component called MdNavbar, which primarily consists of HTML and CSS. The RouteConfig is located in another component where MdNavbar is in ...

A guide on assigning a boolean value to a property during an action using NGXS

Seeking guidance on how to set a boolean value inside an action in NGXS, as I am new to it. Below is the interface I am working with: export interface CertificateObject { certificateName: string; issueDate: Date; expiryDate: Date; thumbPrint: stri ...

Angular 7: struggling to locate the type declaration file

Everything seemed to be working fine with my project yesterday, but today I ran into an issue right after installing the ngx-pagination module: ERROR in src/app/views/dashboard/step1/step1.component.ts(1,23): error TS2688: Cannot find type definition ...

Troubleshooting Nested Handlebars Problem

After creating a customized handlebar that checks for equality in this manner: Handlebars.registerHelper('ifEquals', (arg1, arg2, options) => { if (arg1 == arg2) { return options?.fn(this); } return options?.inverse(t ...

Steps for confirming a property setting on an interface

I am working with the following interface export interface Command { id: CommandId; disabled: boolean; } My goal is to verify that the 'disabled' property has been changed. Here are my attempts: 1) Creating an object and checking if t ...

Request NPM to fetch the complete TypeScript source code, not limited to just the *.d.ts files

Is there a way to request NPM to fetch the TypeScript source files of dependencies, rather than just the *.d.ts and compiled *.js files? I rely on VS Code's Go To Definition feature, but when it comes to dependencies, it only directs me to .d.ts file ...

An improved approach for implementing ngClass condition in Angular components

Searching for a more concise way to rewrite the following condition: [ngClass]="{ 'class1': image.isAvailable && (image.property !== true && !null), 'class2': image.isAvailable && ...

Encountering an error when attempting to show user details on a webpage using Angular and Ionic with Promise functionality

On my app's AccountSettingsPage, I am fetching user data from a SQLite DB and displaying it on an Ionic page. However, I encountered the following error: Error: TypeError: Cannot read property 'name' of undefined at Object.eval [as upd ...

Error TS2307: Module 'angular' could not be located

I have encountered an error in my project and despite searching for solutions, I haven't been able to find one that addresses my specific issue. It seems like a simple problem, but I can't figure out what I'm missing. The error arises in th ...

The error message "Cannot read property 'firestore' of undefined" is often encountered when

I developed an Angular application to test Firebase functions and deployed it on Firebase hosting. Almost everything is working except for the Firestore function, which is causing this error: main.8ae925009adf8b80e1bc.js:1 ERROR Error: Uncaught (in promis ...

JSON Object Key passed as a parameter in a function

While I have seen a similar question before, I am still unsure how to apply the solution in my specific case. I am working with a function that returns a stringified JSON object, but I need to modify one of the keys using a parameter within the function. ...

Oops! Looks like we've encountered a bit of a snag: HttpClient provider is missing

I am currently facing an issue with my code in Testing.ts file. Below is the code segment from Testing.ts: let injector = ReflectiveInjector.resolveAndCreate([ TestService ]) var myInstance = new myTest(injector.get(TestService)); The TestService.ts ...

Angular directive for displaying telephone numbers in the USA format

I recently came across a great solution for formatting USA telephone numbers on StackBlitz. However, I'm now wondering how to add the country code "+1" to the beginning of the telephone mask. Ideally, it should look like: +1(123) 234-2345. ...

No provider for aspnetcore-spa routing

I'm using the Yeoman aspnetcore-spa template with Angular 2. There are essentially 3 key files involved: app.module.client.ts app.module.server.ts app.module.shared.ts I have placed my Service in the providers section of app.module.client.ts and t ...

React Hook Form: Reset function triggers changes across all controllers on the page

I encountered an issue with using the reset function to clear my form. When I invoke the reset function, both of my form selects, which are wrapped by a Controller, get cleared even though I only defined default value for one of them. Is there a way to pr ...

What is the best way to define this.someProperty in a React component using TypeScript?

I'm encountering an issue with TS2339: Property 'someProperty' does not exist on type ''. I am attempting to add a new property to my React component using this.someProperty. interface MyComponentState { allClear: boo ...

The mat table is not displaying the values from the API despite receiving the correct array

I recently made the decision to dive into learning Angular, but I've encountered some difficulties. Specifically, I'm struggling to populate a table with values retrieved from an API using MatTable. Despite receiving the correct values from the A ...

Executing asynchronous dispatch in TypeScript from a frontend component

Within this tutorial found at https://redux.js.org/advanced/exampleredditapi, specifically in the section housing containers/AsyncApp.js, you will notice a snippet of code like so: componentDidMount() { const { dispatch, selectedSubreddit } = this.props ...

Explain the const/type pattern in TypeScript

const INCREMENT_ENTHUSIASM_LEVEL = 'INCREMENT_ENTHUSIASM_LEVEL'; type INCREMENT_ENTHUSIASM_LEVEL = typeof INCREMENT_ENTHUSIASM_LEVEL; const DECREMENT_ENTHUSIASM_LEVEL = 'DECREMENT_ENTHUSIASM_LEVEL'; type DECREMENT_ENTHUSIASM_LEVEL = t ...