2017-12-08 11 views
1

私の約束についての理解は完璧ではありません。
エラーと例外のケースを処理するコードがわかりません。try-catchまたはpromise.catchへのpromise.rejectの処理

コードを正しく記述するのに役立ちます。

1st。試す - のtry-catchがsequelizerのpromise.catchをキャッチすることができます場合はキャッチをsequelizerのpromise.rejectこのため

async function doGetAdminList(adminName) { 

     let adminList; 
     try { 
     adminList = await sequelize.query(
      sqls.GET_ADMIN_LIST, 
      { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT } 
     ); 
     } catch (e) { 
     return Promise.reject({status:500, message: "SQL Error" }); 
     }  

     if (!adminList || !Object.keys(adminList).length) { 
     log.info('\nadminList not found :\n'); 
     return Promise.reject({status:400, message: 'adminList not found.' }) 
     } 

     return adminList; 
    } 

のために、私は疑問に思います()。

第2位。 sequelizerのpromise.rejectにこのために

async function doGetAdminList(adminName) { 
      let adminList; 
      adminList = await sequelize.query(
       sqls.GET_ADMIN_LIST, 
       { replacements: { adminName: adminName }, type: sequelize.QueryTypes.SELECT } 
     ); 

      if (!adminList || !Object.keys(adminList).length) { 
      log.info('\nadminList not found :\n'); 
      return Promise.reject({status:400, message: 'adminList not found.' }) 
      } 

      return adminList; 
     } 

を処理していない、私はsequelizerのpromise.reject()は、呼び出し元の関数を渡され、()promise.catchで、呼び出し元のをcatchedことができますかしら。

上記のsequelize-using関数は、express関数の下で使用されます。

adminController.js

const jwtAuth = require('../common/jwtAuth.js'); 

exports.getAdminList = function (req, res) { 
    res.setHeader("Content-Type", "application/json; charset=utf-8"); 

    if (!req.body.adminName) { 
    return res.status(400).json({ message: 'adminName is empty.' }); 
    } 

    jwtAuth(req.headers.accesstoken) 
    .then((decoded) => { 
    worker = decoded.loginName; 
    return doGetAdminList(adminName); 
    }) 
    .then((adminList) => { 
    log.info("getAdminList() finish"); 
    res.status(200).json(adminList); 
    }) 
    .catch(e => { 
    log.error(e); 
    return res.status(e.status).json(e); 
    }); 
}; 

jwtAuth.jsも機能を約束しています。

const jwt = require('jsonwebtoken'); 
module.exports = async function verifyJwt(token) { 
    return await new Promise((resolve, reject) => { 
    if (!token) { 
     reject({status:401, message:'Empty token'}); 
     return; 
    } 

    jwt.verify(token,"dipa",function(err, decoded){ 
     if(err) { 
     reject({status:401, message:'TokenExpiredError'}); 
     } else { 
     resolve(decoded); 
     } 
    }); 
    }); 
} 
+0

内でgetAdminListをすれば'async function'を使用する場合、' return Promise 'の代わりに 'throw'を使用してください。拒否」 – Bergi

+0

あなたの質問は「*エラーをキャッチしないでください。それともキャッチして別のエラーを再現してはいけませんか?」と思いますか? 'sequelize.query'が' status'を持つオブジェクトで拒否されない場合、SQLエラーを捕捉しないバージョンは動作しません。 – Bergi

+0

@Bergiはい、あなたの権利があります。私は完全に拒否の例外をキャッチ誤解するかもしれません。 – sungyong

答えて

0

async機能がPromiseを返すので、あなたの関数が約束を返す場合は、「非同期」を使用する必要はありません。

私は、var somethink = await doSomethink()の結果は約束しておらず、asyncファンクションから返すので、Promise.resolve(somethink)として返されるということです。

だからあなたの 'jwtAuth.js' は、その優れたなし

const jwt = require('jsonwebtoken'); 
module.exports = function verifyJwt(token) { 
    return new Promise((resolve, reject) => { 
    if (!token) { 
     reject({status:401, message:'Empty token'}); 
     return; 
    } 

    jwt.verify(token,"dipa",function(err, decoded){ 
     if(err) { 
     reject({status:401, message:'TokenExpiredError'}); 
     } else { 
     resolve(decoded); 
     } 
    }); 
    }); 
} 

同じことが

function doGetAdminList(adminName) { 

    let adminList; 

    return sequelize.query(
    sqls.GET_ADMIN_LIST, { 
     replacements: { 
     adminName: adminName 
     }, 
     type: sequelize.QueryTypes.SELECT 
    } 
).catch((e)=> { 
    //here you catch you sequelize error which can be anything 
    //you can either catch and throw a new Error 
    log.info('\nadminList not found :\n'); 
    throw Error({ 
     status: 500, 
     message: "SQL Error" 
    }) 
    }) 

} 

についてgetAdminListと終わりにcatchのために行きます。

jwtAuthまたはdoGetAdminListにエラー.catchがスローされた場合はエラーが発生します。

doGetAdminListにあなたはsequelize.query.catchを行ういけない場合は、sequelize errorはここであなたのcatchに旅行します。しかし、あなたがエラーを処理し、あなたがエラーを再現することができれば可能です。あなたがたいがエラーを変更いけないが、あなたがしたいログやエラーをpassthroudは、あなたがそれをまた

.catch(function(e) { 
    log.info('\nadminList not found :\n'); 
    throw e; 
    }) 

を再スローすることができた場合は、追加

const jwtAuth = require('../common/jwtAuth.js'); 

exports.getAdminList = function (req, res) { 
    res.setHeader("Content-Type", "application/json; charset=utf-8"); 

    if (!req.body.adminName) { 
    res.status(400).json({ message: 'adminName is empty.' }); 
    } 

    jwtAuth(req.headers.accesstoken) 
    .then((decoded) => { 
    worker = decoded.loginName; 
    return doGetAdminList(adminName); 
    }) 
    .then((adminList) => { 
    log.info("getAdminList() finish"); 
    res.status(200).json(adminList); 
    }) 
    .catch(e => { 
    //the message with mess "SQL Error" will travel here. 
    log.error(e); 
    res.status(e.status).json(e); 
    }); 
}; 

あなたのwannaはasync/await

exports.getAdminList = async function(req, res) { 
    res.setHeader("Content-Type", "application/json; charset=utf-8"); 

    if (!req.body.adminName) 
    res.status(400).json({message: 'adminName is empty.'}); 

    try { 

    let decoded = await jwtAuth(req.headers.accesstoken) 
    worker = decoded.loginName; 

    let adminList = await doGetAdminList(req.body.adminName); 
    log.info("getAdminList() finish"); 

    res.status(200).json(adminList); 

    } catch (e) { 
    //the message with mess "SQL Error" will travel here. 
    log.error(e); 
    res.status(e.status).json(e); 
    } 

}; 
+0

'async' /' await'を使うことができるときに 'then'チェーンを使用する理由はありませんか?もちろん、 'verifyJwt'ではそれは余計ですが、' adminlist'ではかなり有益です。 – Bergi

関連する問題