TypeScript - the instanceof operator is incompatible with JSON

Currently, I am utilizing IONIC version 3.0.1 and endeavoring to identify the error type that is being returned from the server. Here are some examples of the error responses:

// HTTP Errors
{"error":"unauthorized","error_description":"long error description"}

// Java Exception
{"timestamp":00000000000,"status":500,"error":"Internal Server Error","exception":"java.lang.Exception","message":"Java Exception","path":"/app/login"}

To address these different errors, I have crafted specific classes for each:

// For HTTP Error
export class HTTPError {
  constructor() {

  }

  public error: string;
  public error_description: string;
}


// For Java Error
export class JavaError {
  constructor() {

  }

  public error: string;
  public exception: string;
  public message: string;
  public path: string;
  public status: number;
  public timestamp: Date;
}

My goal is to pinpoint the error type using the instanceof keyword within my code:

...
let error: any = JSON.parse(response);
if (error instanceof HTTPError) {
  // Condition Block 1
} else if (error instanceof JavaError) {
  // Condition Block 2
} else {
  // Condition Block 3
}
...

Despite efforts, every response leads to the execution of Condition Block 3. The conditions within the if statements persistently return false.

The question remains - what could be the issue in my approach?

Answer №1

When using JSON.parse, the resulting Object does not have a prototype, rendering instanceof ineffective. If your JSON data includes "type" information, you can use that for comparison or check for specific properties to determine the correct object.</p>

<p>Your only option is to verify if it contains any property that corresponds to a specific class.</p>

<pre><code>if(error.error){
   if(error.error_description){
       // This is an HttpError
   }
   else if(error.exception){
       // This is a JavaError
   }
}else{
     // Success...
}

Answer №2

Attempting to reach "condition 1" or "condition 2" is futile because the 'instanceof' operator evaluates prototype chains:

The instanceof operator checks if the prototype property of a constructor exists anywhere in an object's prototype chain.

The output of JSON.parse() is:

The Object associated with the provided JSON text.

JSON.parse() does not determine specific types; it simply produces an Object instance, rather than an instance of HTTPError or JavaError. To handle this, special properties should be checked instead of utilizing the instanceof operator:

...
let resp: any = JSON.parse(response);
if (resp.error) {
   if (resp.error_description) {
      // process HTTPError
   } else if (resp.exception) {
      // process JavaError
   }
}
...

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 method for invoking a JSON web service with jQuery that necessitates basic authentication?

My knowledge of javascript is limited, but I am attempting to access a JSON web service that requires basic authentication using jQuery. Unfortunately, my searches on Google have not yielded any useful results. Can anyone tell me if what I am trying to a ...

Developing an NPM launch command within package.json

Looking to create a script that starts localhost when npm start is entered. Here's what I currently have in my package.json: "scripts": { "start": "npm run open", "open": "concurrently \"http-server -a localhost -p 1234\" \"sle ...

The combination of select2 and jsonform is not functioning properly

I am having trouble rendering multiple select2 with JSON form. $('#resource-form').jsonForm({ schema: { rest: { type: 'object', properties: { template_id: { type: "array", items: { ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Updating a field within an array of objects in Node.js and MongoDB: A step-by-step guide

My main objective is to change the value of the field "done" to "true" I am currently working on a project using nodejs Below is the document for reference: { "_id" : ObjectId("5a730e55114dbc2a0455c630"), "email" : "<a href="/cdn-cgi/l/email-protect ...

Is it necessary to manually validate parameters in TypeScript when developing a library?

Understanding the basic workings of TypeScript, it's clear that TypeScript transpiles code to JavaScript without adding extra behavior like type checking during execution. For instance, function example(parameter: string): void { console.log(paramet ...

Analyzing memory consumption by an individual function in a Node.js environment

Our current experiment involves measuring the memory usage of specific functions. Initially, we attempted to utilize process.memoryUsage().heapUsed before and after calling the function, but encountered issues due to the behavior of the garbage collector. ...

Electron window widens but does not shrink in size

Currently, I am utilizing electron to create an application where I am using ipc messages to expand and retract the width of the app. The frontend is able to trigger these ipc messages successfully, but for some reason, it refuses to go back to a width of ...

"Utilizing Laravel to log errors in various channels and outputting them in JSON

While logging my data in a file using the Laravel framework, I noticed that each log entry comes with an automatically generated string and date: [2021-05-24 17:16:54] local.INFO: {"request":"{\"mail_data\":\"[ ...

Using Javascript to extract elements from JSON objects

This is the output I receive after executing a script. { "log": { "entries": [{ "startedDateTime": "2020-12-01T08:45:30.123Z", "time": 50, "request": { "method": "GET", ...

Adding a second interface to a Prop in Typescript React: a step-by-step guide

import { ReactNode, DetailedHTMLProps, FormHTMLAttributes } from "react"; import { FieldValues, SubmitHandler, useForm, UseFormReturn, } from "react-hook-form"; // I am looking to incorporate the DetailedHTMLProps<FormHTMLAt ...

Decipher intricate JSON data using VB.net in conjunction with Newtonsoft.Json

My project involves developing a Windows application in VB.NET that will receive a daily JSON file, parse its content, and store the extracted values in a SQL database. The challenge I am currently facing lies in effectively parsing the JSON data to retrie ...

Incorporating a unique variant with Tailwind called "

I'm currently struggling with inputting the configuration file for Tailwind. Despite my efforts, I cannot seem to get it right. The code appears correct to me, but I am unsure of what mistake I might be making. Below is the snippet of my code: import ...

Exploring the Children Property in TypeScript and the Latest Version of React

Within my App.tsx file, I am passing <Left /> and <Right /> as components to an imported component named <SplitScreen />. It seems that in React 18, the "children" prop needs to be explicitly typed. When I type it as React.Element[], eve ...

Apollo-Server presents errors in a polished manner

It seems like the question explains itself adequately. I am currently using 'apollo-server-core' version 3.6.5 Desired Errors: { "errors": [ { "message": "Syntax Error: Unexpected < ...

Error encountered: JSON Exception - Unable to locate the key "Name" in the JSONObject

I am looking to retrieve the value "Automation Admin" from the JSON output below, but I keep encountering a JSONObject["Name"] not found exception. https://i.sstatic.net/J6Sfo.png Here is the code snippet: https://i.sstatic.net/zjR2w.png I attempted to ...

Enhancing User Experience with AJAX and JSON in Servlet JSP Applications

I've been working on my school project for a while, but I'm having trouble with the login page. Every time I try to log in, I receive a PARSING ERROR message like this: Error Login AJAX For the login process, I am using a simple servlet that co ...

Is there a way to parse through a collection of JSON strings in Python without using keys?

My code utilizes json.dumps and generates the following JSON structure: [{ "name": "Luke", "surname": "Skywalker", "age": 34 }, { "name": "Han", "surname": "Solo", &q ...

Creating Instances of Parameterized Types

Consider the following scenario: class Datum {} An error message (error TS2304: Cannot find name 'T') is encountered when attempting the following: class Data<T extends Datum> { datum: T constructor() { this.datum = new ...

Issue with jQuery tooltip not showing information when there is a space present

I am attempting to display data on a mouse hover event using a jQuery tooltip. The data I have looks like this: {"description":"marry christmas","date":"2016-12-25}" which I received from the server as a JSON string. I am parsing it in my calendar as follo ...