Skip to content Skip to sidebar Skip to footer

Angular2 Exceptionhandler - Check If Error Object Is Response

I am currently using the following code to handle exceptions: @Injectable() export class CustomExceptionHandler extends ExceptionHandler { call(error, stackTrace = null, reason =

Solution 1:

Interesting question. Since TypeScript is really just compiling down to JS, classes don't really exist. I can think of two ways you could check, you can use a "User-Defined Type Guard" or use the "instanceof type guard". The User-Defined Type Guard is just a fancy way of checking a property/function of the object to determine its Type, the advantage is TS won't complain about a "missing property/function". Using the "instanceof" works but only if the Object has a constructor as it's comparing the two Object's constructors. So if your Object doesn't have a constructor it's a no go. You can find the documentation for these two here.

I also made a plunker demonstrating how they work. The results will load into the console, so use your browsers debug tool to see the results. All the work is being done on "app/child.component.ts" in the "ngOnChanges" function.

ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
  console.log();
  console.log("Custom function isSimpleChange:", this.isSimpleChange(changes));
  console.log("Using instanceof SimpleChange:", (changes instanceofSimpleChange));
  console.log("Using Object.prototype.toString.call():", Object.prototype.toString.call(changes));
  console.log("Logging the object itself:",changes);
  console.log("-----------------------------------------------------------------------------------------");
  let testExample = newExampleObject();
  console.log("Custom function isExampleObject:", this.isExampleObject(testExample));
  console.log("Using instanceof ExampleObject:", (testExample instanceofExampleObject));
  console.log("Using Object.prototype.toString.call():" + Object.prototype.toString.call(testExample));
  console.log(testExample);


  this._result = changes.value.currentValue;
  this._changes++;
}

You will probably need to leverage both and also "typeof" for your primitive types to do a complete inspection of the object. So using "typeof" to check for basic types "string","number","boolean". Then using "instanceof" to see if the constructors match, finally using a "User-Defined Type Guard" to look for specific "properties/functions".

Post a Comment for "Angular2 Exceptionhandler - Check If Error Object Is Response"