Lets take in account the "Problem with throwing" section, and rewrite the code.
classUserNotFoundextendsError{constructor(message:string='User not found'){super(message);this.name='UserNotFound';}}classUserNotActiveextendsError{constructor(message:string='User is not active'){super(message);this.name='UserNotActive';}}asyncfunctiongetUser(id:string):Promise<User|UserNotFound|UserNotActive>{constuser=awaitdb.query(`SELECT * FROM users WHERE id = ?`,[id]);if (!user){returnnewUserNotFound();}if (!user.isActive){returnnewUserNotActive();}returnuser;}
The function signature is not lying to you anymore
You know what output types to expect
You are forced to check the output type
The errors have context
The extra benefit is that the errors are checked on class name instead of on a string. This reduces errors by typos.
The main driver in the Result solution is that instead of throwing the errors they are returned. So you don't need the type to make the solution happen.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Lets take in account the "Problem with throwing" section, and rewrite the code.
The extra benefit is that the errors are checked on class name instead of on a string. This reduces errors by typos.
The main driver in the
Resultsolution is that instead of throwing the errors they are returned. So you don't need the type to make the solution happen.