所以我正在寻找一个关于如何处理异常的模式。具体而言,我希望能够通过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