Correct error pattern for asynchronous functions using Promises in TypeScript

I want to make a typed asynchronous function with proper error handling.

I can define one like this:

export async function doSomething(userId:string) : Promise<ISomething | void> {

    let somthing: ISomething = {};

    try {
        something.user = await UserDocument.findById(userId);
        something.pet = await PetDocument.findOne({ownerId:userId});
        return Promise.resolve(something);
    } catch (err){
        console.log("I would do some stuff here but I also want to have the caller get the error.");
        return Promise.reject(err);
    }
}

... which works, but (for obvious reasons), if I try to assign a result to an object ISomething, I get an error message Type 'void | ISomething' is not assignable to type 'ISomething'.

let iSomething:ISomething;
iSomething = await doSomething('12'); //this give me the error

I understand why this is so. My question is: which template should I use for error handling in this case? Note that if the return type is Promise<IProfile>instead, I get an error for the string return Promise.reject(err);(which will return Profile<void>).

return Promise.reject(err); throw err;, , Promise.reject (, , ).

, - promises/async, , .

... , Promise, :

doSomething('12')
  .then( (something) => {//do stuff})
  .catch( (err) => {//handle error});

throw Promise.reject? throw, .catch() ?

+4
2

, , async:

export async function doSomething(userId:string) : Promise<ISomething>{

    let something: ISomething = {};

    try {
        something.user = await UserDocument.findById(userId);
        something.pet = await PetDocument.findOne({ownerId:userId});
        return something;
    } catch (err){
        console.log("I would do some stuff here but I also want to have the caller get the error.");
        throw(err);
    }
}

, , :

export async function doSomething(userId:string) : Promise<ISomething>{    
    let something: ISomething = {};
    something.user = await UserDocument.findById(userId);
    something.pet = await PetDocument.findOne({ownerId:userId});
    return something;
}

+1

, Promise.reject Promise.resolve, - .

| void , return Promise.reject<ISomething>(err);. !

:

export async function doSomething(userId:string) : Promise<ISomething> {

    let something: ISomething = {};

    try {
        something.user = await UserDocument.findById(userId);
        something.pet = await PetDocument.findOne({ownerId:userId});
        return Promise.resolve(something);
    } catch (err){
        console.log("I would do some stuff here but I also want to have the caller get the error.");
        return Promise.reject<ISomething>(err);
    }
}
0

Source: https://habr.com/ru/post/1667823/


All Articles