2015-05-29 50 views
4

我有一個下面的Restify自定義錯誤,它被引發到我的BlueBird Promise catch塊。Restify返回undefined不是錯誤對象中的函數

var test = function() { 
    respObject = { hello: { world: 'aasas' } }; 
    throw new restify.errors.ServiceError(respObject, 422); 
} 

然後在服務錯誤:

function ServiceError(respObject, statusCode) { 
    restify.RestError.call(this, { 
    restCode: 'ApiError', 
    statusCode, statusCode, 
    message: 'Api Error Occurred', 
    constructorOpt: ServiceError, 
    body: { 
     message: 'Api Error Occurrede', 
     errors: respObject.toJSON() 
    } 
    }); 

    this.name = 'CustomApiError'; 
} 

util.inherits(ServiceError, restify.RestError); 
restify.errors.ServiceError = ServiceError; 
但是對 test()調用函數

test().catch(function(err) { 
    console.log(err); 
}); 

它返回undefined is not a function。是否有一個原因,爲什麼它不返回到catch塊的上述調用函數的對象?

+0

會發生什麼 - 是它正常工作?我不明白你如何得到'undefined不是一個函數'.. –

+0

@AndreyPopov如果我去拋出新的錯誤('測試')'我得到正確的錯誤對象。這只是與Restify自定義錯誤,似乎並不工作 –

回答

0

我找到了答案。這是respObject.toJSON()這是造成undefined is not a function因爲respObject沒有toJSON()功能:)如果你只是在```test`拋出新的錯誤(「測試」)

3

問題不在Restify中,它與您的test函數不同。你打電話test().catch,但test()不返回任何東西 - 即。它返回undefined。你基本上調用undefined.catch,它不存在。

如果您想對test的結果致電catch,則需要返回承諾。

+0

好眼(笑) –

+0

我不知道這是否正確。它會拋出一個異常,最終導致catch塊。即使你在異常之後返回,它也永遠不會在那裏結束 –

+1

你沒有'catch'塊。這看起來像這樣:'try {test(); } catch(err){console.log(err); }'你試圖調用一個名爲'catch'的函數,但是你沒有返回一個具有'catch'函數的對象。 –