Properly capturing an item within a TypeScript catch statement

I am dealing with a scenario where my function might throw an object as an error in TypeScript. The challenge is that the object being thrown is not of type Error. How can I effectively handle this situation?

For example:

function throwsSomeError() {
  throw { code: 10, message: 'error' }
}

try {
  throwsSomeError()
} catch (error: unknown) {
  const message = error?.message;
  //              ^^ Object is of type 'unknown'.(2571)
}

Try on TypeScript Playground

Answer №1

Discover how to type catch clauses in TypeScript here

When handling errors in TypeScript, you can determine the data type of the error without explicitly specifying it in the catch parameter.

try {
  throwsSomeError()
} catch (error) {
  if (error instanceof Error) {
    const message = error?.message;
  } else {
    // handle other types of errors
  }
}

Edit:

I recommend creating a custom error class to identify the specific type of error object.

class CustomError extends Error {
    code?: number
    constructor(code?: number, message?: string) {
        super(message);
        this.code = code
    }
}


function throwsSomeError() {
  throw new CustomError(10, 'An error occurred')
}

try {
  throwsSomeError()
} catch (error) {
  if (error instanceof CustomError) {
    const message = error?.message;
  } else {
    // handle other errors
  }
}

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

Developing an object using class and generic features in Typescript

I am currently working on creating a function or method that can generate sorting options from an array. One example is when using Mikro-ORM, where there is a type called FindOptions<T> that can be filled with the desired sorting order for database q ...

Issue with TypeScript: Difficulty accessing keys in a recursive manner

I've created a custom type that eliminates any nullish values when working with objects. export type ExcludeNullish<T> = Exclude<T, null | undefined>; export type ExcludeNullishKeys<T> = { [K in keyof T]-?: T[K] extends boolean | ...

Using TypeScript to pass objects to an arrow function

Issue at Hand: How do I successfully transfer an object from a parent component to a child component that is derived from the same interface? I am currently facing difficulties in rendering a list of tasks by looping through a list of task objects. The ma ...

Exploring the intricacies of pattern matching with JavaScript visualization

I am currently working on improving my pattern matching function by creating a visualizer for it. To achieve this, I need to slow down the execution of each comparison. My approach involves declaring the i and j variables outside of the function so that I ...

Circular structure error occurred when attempting to convert an object to JSON, starting at an object constructed with the constructor 'Object'

I am facing an issue where I need to update a Medico from the collection, and I have successfully destructured the data of the Medico's name and email. Additionally, I have obtained the ID of the assigned hospital. However, I am having trouble sendin ...

Executing additional code after all tests have finished in Mocha.js

In the world of MochaJS testing, it is customary to have before and after blocks for setup and teardown operations. But what if we want to execute an extra cleanup step after all test files have been processed? This is crucial to ensure that any lingering ...

Using Vuelidate with Vue 3, vue-class-component, and TypeScript combination

Is there anyone who has successfully implemented Vuelidate with Vue 3 using the Composition API? Although Vuelidate is still in alpha for Vue 3, I believe that if it works with the Composition API, there must be a way to make it work with classes as well. ...

What could be causing the CSS loader in webpack to malfunction?

I am currently working on implementing the toy example mentioned in the css-loader documentation which can be found at https://github.com/webpack-contrib/css-loader Additionally, I have also followed a basic guide that recommends similar steps: https://cs ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

Error encountered: No matching overload found for MUI styled TypeScript

I am encountering an issue: No overload matches this call. Looking for a solution to fix this problem. I am attempting to design a customized button. While I have successfully created the button, I am facing the aforementioned error. Below is my code ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

The process of inserting data into MongoDB using Mongoose with TypeScript

Recently, I encountered an issue while trying to insert data into a MongoDB database using a TypeScript code for a CRUD API. The problem arises when using the mongoose package specifically designed for MongoDB integration. import Transaction from 'mon ...

The type 'LoadableComponent<unknown>' cannot be assigned to type 'ReactNode'

Currently in the process of migrating from react-router-dom v5 to v6. // Original code using react-router-dom v5 <Route exact path="/" component={router.Home} /> // Updated code for react-router-dom v6 <Route path="/*" element ...

Converting a Promise to an Observable in Angular using Typescript

I have a working method that functions as intended: getdata(): Promise<any> { let query = `SELECT * FROM table`; return new Promise((resolve, reject) => { this.db.query(query, (error, rows) => { if(error) reject(error); ...

Utilizing the map function to incorporate numerous elements into the state

I'm struggling with 2 buttons, Single Component and Multiple Component. Upon clicking Multiple Component, my expectation is for it to add 3 components, but instead, it only adds 1. import React, { useState, useEffect } from "react"; import ...

Adding markers to a map in Angular 2 using ngOnInit after initialization

Embarking on my Angular journey by creating a sample app incorporating GoogleMaps. import { Component, Input, OnInit, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { FormControl } from '@ ...

What is the process for ensuring that the "ng-multiselect-dropdown" is a mandatory field within Angular 7?

Is there a way to require the ng-multiselect-dropdown field to have at least one selected item? <ng-multiselect-dropdown [placeholder]="'Select countries'" [data]="countries" [(ngModel)]="countriesSelectedItems" [settings]="co ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...