在Node.js Express中处理未处理的承诺拒绝

时间:2019-06-28 04:23:08

标签: javascript node.js express promise async-await

我有一个Promise异步功能,我想知道如何捕获express / nodejs中的所有错误

如果getData1的网址无效,应用程序将停止声明private void dialogForm(){ dialog = new AlertDialog.Builder(MainActivity.this); inflater = getLayoutInflater(); dialogView = inflater.inflate(R.layout.macro_form, null); dialog.setView(dialogView); dialog.setCancelable(true); dialog.setIcon(R.mipmap.ic_launcher); dialog.setTitle("Macro Form"); txtMacroName = (EditText) dialogView.findViewById(R.id.txtMacroName); txtMacroStatus = (EditText) dialogView.findViewById(R.id.txtMacroValue); dialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { macroName = txtMacroName.getText().toString(); macroStatus = txtMacroStatus.getText().toString(); dialog.dismiss(); } }); dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.show(); } ,如何正确处理错误而不会导致应用程序崩溃。

unhandled promise rejection failed to fetch value

1 个答案:

答案 0 :(得分:0)

  module.exports.getData1 = function () {
return new Promise(async function (resolve, reject) {
    url = 'https://jsonplaceholder.typicode.com/todos/';
    await request.get({ url }, (err, response, body) => {
        if (!err && response.statusCode == 200) {
            resolve(JSON.parse(body));
        }
        else if (response.statusCode >= 400 && response.statusCode <= 500) {
            reject(new Error({ errors: response.statusCode + "Error" }));
        }
        else {
            reject(new Error({ errors: response.statusCode + ": Not authorised to access requested data" }));
        }
    })
}).catch((err)=>{
    reject(new Error("failed to fetch value"));//don't understand why a reject here because catch only works when a promise is rejected.
    console.log(err)// or have an explicit error class and assign its properties
    throw new Error(err);
});

}

您可以使用承诺中的拒绝,这会被捕获在catch部分中,您可以在其中重新引发此错误。