TypeScript: identifying the specific error type within a catch block

I am currently working on a project using typescript in combination with VueJS

Despite my efforts, I encountered a type error in my code

I tried using type assertation to resolve the issue

However, the error persists

catch (err) {
  
   const  msg = (err as TypeError)?.response?.statusText
}

Can anyone suggest what steps I should take to address this problem?

Answer №1

If you are facing a problem, one way to address it is by verifying if err truly corresponds to a TypeError. You can achieve this with the following snippet:

catch (err) {

   if (err instanceof TypeError) {
  
       const  msg = err.response?.statusText

   }
   
}

For further clarification: err has the potential to represent any data in JavaScript, as it allows throwing of diverse elements (although it is recommended to refrain from doing so):

function foo() {
    try {
        throw 'this is not an error'; // avoid this practice!
    } catch (err) {

        if (err instanceof Error) {
            console.error('error', err);
        } else {
            console.log('log', err);
        }
    }
}

foo(); // outputs: log this is not an error

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

What is the process for sending an http get request that provides a JSON array to populate an ngFor directive?

I'm trying to figure out how to make an http get request in order to retrieve a json array of data that I can use within an ngFor loop. The list that needs to be looped through is stored in this.list. Currently, the json file for testing purposes is l ...

Ionic2: expanding menu options in the sidemenu

I'm not very familiar with ionic, but I have a question on behalf of my friend who is hesitant to ask on StackOverflow because she's unsure of how to frame her question. She simply wants to learn how to implement a submenu in an ionic 2 side men ...

Adjusting an item according to a specified pathway

I am currently working on dynamically modifying an object based on a given path, but I am encountering some difficulties in the process. I have managed to create a method that retrieves values at a specified path, and now I need to update values at that pa ...

Obtain an instance tuple from tuple classes using TypeScript 3.0 generic rest tuples type

When it comes to retrieving the correct instance type from a class type, the process typically involves using the following code: type Constructor<T = {}> = new (...args: any[]) => T class Foo {} function getInstanceFromClass<T>(Klass: Co ...

How can methods access variables from the Vuex store during function calls?

Within my Vue.js component, there is a v-select element. Upon user selection in this widget, the toDo function is triggered from the methods block. However, when attempting to access the value of the filters getter within this function, it consistently ret ...

Group of objects containing an inner group of objects

Here is an array of objects that I am working with: let prova: ActiveRoute[] = [ { path: '/Root', method: 'GET', children: [ { path: '/Son', method: 'GET', chi ...

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

How to retrieve an array stored within a JSON object

I am trying to access a specific array within an object from a JSON file. Here is the snippet of the data I'm dealing with: best-sellers": [ { "title": "Chuteira Nike HyperVenomX Proximo II Society", "price": 499.90, "installmen ...

How come Vue.js is not showing the image I uploaded?

Even though I can successfully print the image URL, I'm facing an issue where the img tag is not displaying it, despite my belief that I've bound it correctly. <html> <head> <title>VueJS Split Demo</title> <script t ...

Avoid Vue Multiple Select from Saving an Empty Array

I need the select multiple feature to automatically pre-select one option and prevent users from deselecting all options. If the last selected option is deselected, it should automatically be reselected. Essentially, the last option cannot be visually des ...

Is there a way to limit the typing of `T extends {}` so that `keyof T` is always a string?

My current mapping type has been effective in many scenarios: type WithKeyPrefix<P extends string, T extends {}> = { [K in Extract<keyof T, string> as `${P}/${K}`]: T[K]; }; However, I'm facing an issue with rejecting objects that have ...

Examining the asynchronous function to cause an error using mocha

I am facing a challenge with testing an async function that is supposed to run for 2000ms before throwing an exception. Despite my efforts using Mocha / chai, the test does not seem to be working as expected. Here's what I have attempted: First appr ...

Change a TypeScript alias within the @types namespace

While using Typescript 3, I encountered a situation where I needed to modify a type alias from the @types/json-schema definition provided by DefinitelyTyped. The issue arose when I wanted to incorporate a custom schema type into my code. Since this custom ...

TypeScript(error:2532): object may be undefined despite null or undefined check

Currently, I am developing a Discord-bot using TypeScript which includes a command to retrieve information from an airport. To do this, users only need to provide the 4-character ICAO code that identifies the specific airport. However, due to potential use ...

The error message from ANGULAR states that it cannot locate the control with the specified path: 'childrenFormArray -> [object Object] -> gender'

I'm currently working on an angular project and facing a challenge in adding multiple children with their age and gender dynamically using reactive forms. Although I can add the form, I am having trouble with the delete functionality as it keeps throw ...

What is the best way to display user data exclusively in Angular?

How can I ensure that users only have access to their own information rather than the entire database? I attempted to use an if-else statement to filter out the data I need, as shown in the example below, but it was unsuccessful. custom-history.component ...

Utilize Typescript to inject types into a library

I have a code snippet that reads data from a JSON file and creates a type based on it, which is then used for further operations. import jsonData from './mydata.json' type CustomType = typeof jsonData .... This process ensures that the generate ...

using vuejs to pass a function as a prop

As I work on creating a foundational "TableComponent," incorporating selectable rows and more, I am faced with the requirement for this TableComponent to accept a prop named "buttons." These buttons are expected to be in the form of an array of objects ...

Make sure to verify if the mode in Angular is either visible-print or hidden-print

Here is a snippet of code <div class="row"> <div class="col-sm-12 visible-print"> Content (display in full width when printed) </div> <div class="col-sm-6 hidden-print"> Content (same as above but only half width when ...

Adding URL path in Angular 7's .ts file

I currently have the following code in my component's HTML file: <button mat-flat-button class="mat-flat-button mat-accent ng-star-inserted" color="accent" (click)="playVideo(video)"> <mat-icon [svgIcon]="video.type === 'external' ...