所以我正在尋找一個關於如何處理異常的模式。具體而言,我希望能夠通過Web API控制器將異常消息傳遞給客戶端。Web api和角度2客戶端之間的錯誤處理
的客戶端使用第三方庫,以作爲
this.msgs = [];
let xhr = new XMLHttpRequest(),
formData = new FormData();
for(let i = 0; i < this.files.length; i++) {
formData.append(this.name, this.files[i], this.files[i].name);
}
xhr.upload.addEventListener('progress', (e: ProgressEvent) => {
if(e.lengthComputable) {
this.progress = Math.round((e.loaded * 100)/e.total);
}
}, false);
xhr.onreadystatechange =() => {
if(xhr.readyState == 4) {
this.progress = 0;
if(xhr.status == 200)
this.onUpload.emit({xhr: xhr, files: this.files});
else
this.onError.emit({xhr: xhr, files: this.files});
this.clear();
}
};
xhr.open('POST', this.url, true);
xhr.send(formData);
我目前的回調函數的API 呼叫涉及這樣
errorComplete(event: any) {
console.log("upload error");
}
通知,對錯誤的圖書館剛包裝XMLHttpRequest並將其傳遞給我的回調函數。
所以在控制我創建了一個測試線如下
throw new Exception("This is a test message");
這是模擬一個意外的異常
目前在XMLHttpRequest的返回代碼是500,文本是HTML .Net在發生異常時生成。
yes我的控制器中的方法需要包裝在try-catch中,但我不確定要在catch中放置什麼代碼,以便我可以將錯誤消息發送到客戶端,並且它可以處理它而不是取下應用程序。
我正在查看的當前用例是用戶上傳文件到系統,但系統中已經有一個具有指定名稱的文件。重命名文件不是一個選項!我需要通知用戶系統中已有一個具有該名稱的文件。
谷歌還沒有透露一種方式來傳遞消息,所以我可以處理它。
不要在控制器中使用try catch。通過ExceptionHandler派生類使用橫切關注點。讓那個類返回你的錯誤代碼和正文。通常500內部服務器錯誤。正文可以具有特定於應用程序的任何自定義細節 – Nkosi