Reputation: 756
I'm trying to personalize my error classes inside the application.
I have totally four classes; Exception, GenericError, BaseService, CarService two main and two inherited. GenericError extends ExceptionClass and CarService extends BaseService. I'm not be able to change constructor property of GenericError class. I'm getting this error;
This expression is not constructable.
What is wrong with my class inheritence logic?
// Exception.ts
class ExceptionClass extends Error {
status: number;
message: string;
errors?: object;
constructor(status: number, message: string, errors?: object) {
super(message);
this.status = status;
this.message = message;
this.errors = errors;
}
}
// GenericError.ts
class GenericException extends ExceptionClass {
constructor(message?: string) {
super(400, message || 'Internal Error');
}
}
// BaseService.ts
class BaseService {
genericError: GenericException;
constructor(message: string) {
this.genericError = new GenericException();
}
}
// CarService.ts
export default class CarService extends BaseService {
constructor() {
super('')
console.log("CarService started!");
}
async checkCar() {
return new Promise(async (resolve: any, reject: any) => {
//** Imagine some business logic that fails */
const passwordsNotMatchErr = new this.genericError('Fail Reason bla bla');
return reject(passwordsNotMatchErr);
})
}
}
Upvotes: 1
Views: 4468
Reputation: 447
The problem is that in the following line:
const passwordsNotMatchErr = new this.genericError('Fail Reason bla bla');
You are trying to create an instance of a variable that has been instantiated in the constructor of your class. You are trying to do something like const myString = new "I am a string and I can not be instantiated"
When you do:
genericError: GenericException;
What you are doing is defining a class variable which is of GenericExpection
type (Remember that only classes can be instantiated, not variables). If you'd like to follow your architecture you can do something like:
async checkCar() {
return new Promise(async (resolve: any, reject: any) => {
//** Imagine some business logic that fails */
this.genericError = new GenericException('Fail Reason bla bla');
return reject(this.genericError);
})
}
or
async checkCar() {
return new Promise(async (resolve: any, reject: any) => {
//** Imagine some business logic that fails */
const passwordsNotMatchErr = new GenericException('Fail Reason bla bla');
return reject(passwordsNotMatchErr);
})
}
Upvotes: 3