asyncfunctionhandleRequest(req:Response,res:Request){const{user,error}=awaitgetUserData(1);if(error){returnres.status(400).json({error})}res.status(200).json({user})}interfaceUserData{name:stringage:number}typeUserResponse={user:UserData|null,error:string|null}asyncfunctiongetUserData(id:number):Promise<UserResponse>{if(id<=0){return{user:null,error:"Wrong, id can't be less or equal to zero!!!"// Why this failed}}return{user:{name:"Jimmy",age:22},error:null}}
Or I'd just throw an error inside the getUserData function
asyncfunctionhandleRequest(){try{const{user}=awaitgetUserData(1);const{user:user2}=awaitgetUserData(1);console.log(user,user2);}catch(e){console.error(e);}}interfaceUserData{name:stringage:number}typeUserResponse={user:UserData|null}asyncfunctiongetUserData(id:number):Promise<UserResponse>{if(id<=0){throwError("Wrong, id can't be less or equal to zero!!!")}else{return{user:{name:"Jimmy",age:22}}}}
Personally, I do not like to handle errors that way, I consider them incorrect, I leave you the link so you can take a look about making these exceptions: developer.mozilla.org/docs/Web/Jav...
asyncfunctiongetUser(id:number):Promise<User>{// We throw an exception.if(id<=0)thrownewError("Wrong, id can't be less or equal to zero!!!");// Result.return{id,email:"abc@domain.com"};}
asyncfunctiongetUserData(id:number):Promise<Result<UserData>>{if(id<=0){return{error:newError("Wrong, id can't be less or equal to zero!!!");}}return{result:{name:"Jimmy",age:22},}}
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.
I usually do
Or I'd just throw an error inside the getUserData function
Thank you for your contribution, my friend.
Personally, I do not like to handle errors that way, I consider them incorrect, I leave you the link so you can take a look about making these exceptions: developer.mozilla.org/docs/Web/Jav...
Now we handle it.
Sure, I actually like the golang pattern because is easy to read.
Also I got a different approach by asking about this.