エラーに対して適切な HTTP ステータス コードを使用し、JSON でエンコードされた応答と適切なContent-Type
ヘッダーで応答する API があります。私の状況では、コールバックではなく、HTTP エラー ステータスが発生したときにコールバックがjQuery.ajax()
トリガーされるため、わかりやすい JSON 応答がある場合でも、次のような方法に頼る必要があります。error
success
$.ajax({
// ...
success: function(response) {
if (response.success) {
console.log('Success!');
console.log(response.data);
} else {
console.log('Failure!');
console.log(response.error);
}
},
error: function(xhr, status, text) {
var response = $.parseJSON(xhr.responseText);
console.log('Failure!');
if (response) {
console.log(response.error);
} else {
// This would mean an invalid response from the server - maybe the site went down or whatever...
}
}
});
jQuery.ajax()
各呼び出しで 2 つの場所で同じエラー処理を行うよりも優れたパラダイムはありますか? あまりDRYではありません。これらの場合の適切なエラー処理プラクティスのどこかで何かを見逃しているに違いありません。