因此,我正在寻找一种如何处理异常的模式。具体地说,我希望能够将异常消息从Web API控制器传递给客户端。
客户端正在使用第三方库,该库将API调用处理为
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);我当前的回调函数是这样的
errorComplete(event: any) {
console.log("upload error");
}请注意,出错时,库只包装XMLHttpRequest并将其传递给我的回调函数。
因此,我在控制器中创建了一个测试行,如下所示
throw new Exception("This is a test message");这是为了模拟一个意外的异常
目前,XMLHttpRequest中的返回码是500,文本是.Net在发生异常时生成的html。
是的,我的控制器中的方法需要包装在try-catch中,但我不确定在catch中放入什么代码,这样我就可以将错误消息发送到客户端,它可以处理它,而不会关闭应用程序。
我正在查看的当前用例是,用户将文件上传到系统,但系统中已存在具有指定名称的文件。并且重命名文件不是一个选项!我需要通知用户系统中已经有一个同名的文件。
谷歌还没有透露一种方法来传递回消息,以便我可以处理它。
发布于 2017-03-31 06:18:15
谢谢你,Nkosi-你的评论让我走上了正确的道路。我实现了一些中间件。
public class UIExceptionHandler
{
RequestDelegate _next;
public UIExceptionHandler(RequestDelegate next)
{
this._next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await this._next(context);
}
catch (Exception x)
{
if (!context.Response.HasStarted)
{
context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
context.Response.Headers["Message"] = x.Message;
}
}
}
}
public static class UIExcetionHandlerExtensions
{
public static IApplicationBuilder UseUIExceptionHandler(this IApplicationBuilder builder)
{
return builder.UseMiddleware<UIExceptionHandler>();
}
}并在启动的configure方法中
app.UseUIExceptionHandler();然后在客户机上我可以
errorComplete(event: any) {
var errorMessage = event.xhr.getResponseHeader('Message');
console.log(errorMessage);
}如果任何人看到此解决方案的问题,请让我知道
https://stackoverflow.com/questions/43102807
复制相似问题