也許你正試圖把所有的錯誤處理代碼放在一個地方。如果是這樣,您可以利用jQuery的ajax方法(或get或其他)實現promise接口,並將任何有風險的代碼放入then函數中。
方法如下:
jQuery.ajax('http://www.someurlthatwillproduceanerror.com/but/only/maybe')
.then(function(data, textStatus, jqXHR) {
// This function handles the response. It is NOT called if the AJAX fails.
console.log('ok');
/** An optional result object to pass to your done() function */
var result;
try {
// Code that might blow up goes here
result = 'The final result';
} catch (e) {
// Oh no—it blew up!
// Reject the promise with the function signature of an AJAX failure
return $.Deferred().reject(jqXHR, textStatus, e);
}
// We only get this far if there wasn't an exception.
return result; // Optional
})
.done(function(result) {
// This function gets called if there were no problems at all.
alert('Well, that\'s just ducky! Contact the vendor ' +
'and tell them to promote their devs!');
console.log('Woo-hoo!', result);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// This function gets called if the AJAX failed, or if there was an exception
alert('Something went wrong. Contact the vendor ' +
'and tell them to give their devs more money!');
console.error('Rats!', jqXHR, textStatus, errorThrown);
});
這樣一來,你有任何意外的錯誤一個失敗()函數,無論是在服務器端或客戶端。
對不起......它不會像工作,因爲你是在處理異步執行 –