[英]How do I throw errors from an action in Seneca?
我正在使用SenecaJS開發一個簡單的任務管理器,並且試圖了解從操作中引發錯誤的正確方法。 假設我有一個從數據存儲區加載任務的操作,但該任務不存在...
下面是我插件的方法:
/**
* Retrieves a task based on a task ID.
*
* @param {number} args.taskID The UUID of the task to be retrieved.
* @param {function} done A callback function which is called upon retrieval. The
* first argument is an error response; the second is the task.
* @returns {Task|undefined} A task if one exists; otherwise undefined.
*/
this.get = function(args, reply) {
var task = this.make('task')
task.load$( args.taskID, function(err, task)
if(!task || err) {
reply( {code:404, message:`Task ${args.taskID} not found.`} );
} else {
reply( task );
}
});
};
這是單元測試:
test('Returns "undefined" for non-existant tasks', (fin) => {
var seneca = testSeneca(fin);
var id = "I-don't-exist";
seneca
.act(
{ domain: 'task', action: 'get', taskID: id },
function(err, result) {
expect(result).not.toBeNull();
expect(result.code).toBe(404);
fin();
}
);
});
下面的代碼有效,但是正如您所看到的,我真的忽略了err回調並評估結果以查看是否為錯誤。 在文檔中,Seneca使用以下引發錯誤:
回復(新錯誤(404));
要么
拋出新的錯誤(404);
但是當我這樣做時,它結束了該過程,並且單元測試失敗了。 此外,即使我回答了兩個對象,err回調也似乎總是為空。
是否有使用err回調返回錯誤的更正確方法?
您可能正在使用插件定義實例來調用常規操作-在這種情況下,錯誤總是致命的,因為它們表示初始化失敗。
嘗試
this.get = function(args, reply, meta) {
console.log(meta)
看看是否fatal === true
。
還請包括您的seneca.add
調用的代碼,以便我們查看是否存在這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.