Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom error class in TypeScript

I'd like to create my own error class in TypeScript, extending core Error to provide better error handling and customized reporting. For example, I want to create an HttpRequestError class with url, response and body passed into its constructor, which reponds with Http request to http://example.com failed with status code 500 and message: Something went wrong and proper stack trace.

How to extend core Error class in TypeScript? I've already found post in SO: How do I extend a host object (e.g. Error) in TypeScript but this solution doesn't work for me. I use TypeScript 1.5.3

Any ideas?

like image 427
Kuba T Avatar asked Jul 25 '15 11:07

Kuba T


People also ask

How do you throw an error in TypeScript?

To declare a function that throws an error, set its return type to never . The never type is used for functions that never return a value, in other words functions that throw an exception or terminate execution of the program.


2 Answers

TypeScript 2.1 had a breaking changes regarding Extending built-ins like Error.

From the TypeScript breaking changes documentation

class FooError extends Error {     constructor(msg: string) {         super(msg);          // Set the prototype explicitly.         Object.setPrototypeOf(this, FooError.prototype);     }      sayHello() {         return "hello " + this.message;     } } 

Then you can use:

let error = new FooError("Something really bad went wrong"); if(error instanceof FooError){    console.log(error.sayHello()); } 
like image 195
ziv Avatar answered Nov 09 '22 03:11

ziv


Until 1.6 rolls around, I've just been making my own extendable classes.

class BaseError {     constructor () {         Error.apply(this, arguments);     } }  BaseError.prototype = new Error();  class HttpRequestError extends BaseError {     constructor (public status: number, public message: string) {         super();         } }  var error = new HttpRequestError(500, 'Server Error');  console.log(     error,     // True     error instanceof HttpRequestError,     // True     error instanceof Error ); 
like image 45
thoughtrepo Avatar answered Nov 09 '22 04:11

thoughtrepo