首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >web api和angular 2客户端之间的错误处理

web api和angular 2客户端之间的错误处理
EN

Stack Overflow用户
提问于 2017-03-30 03:46:19
回答 1查看 1.3K关注 0票数 2

因此,我正在寻找一种如何处理异常的模式。具体地说,我希望能够将异常消息从Web API控制器传递给客户端。

客户端正在使用第三方库,该库将API调用处理为

代码语言:javascript
复制
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);

我当前的回调函数是这样的

代码语言:javascript
复制
errorComplete(event: any) {
    console.log("upload error");
}

请注意,出错时,库只包装XMLHttpRequest并将其传递给我的回调函数。

因此,我在控制器中创建了一个测试行,如下所示

代码语言:javascript
复制
throw new Exception("This is a test message");

这是为了模拟一个意外的异常

目前,XMLHttpRequest中的返回码是500,文本是.Net在发生异常时生成的html。

是的,我的控制器中的方法需要包装在try-catch中,但我不确定在catch中放入什么代码,这样我就可以将错误消息发送到客户端,它可以处理它,而不会关闭应用程序。

我正在查看的当前用例是,用户将文件上传到系统,但系统中已存在具有指定名称的文件。并且重命名文件不是一个选项!我需要通知用户系统中已经有一个同名的文件。

谷歌还没有透露一种方法来传递回消息,以便我可以处理它。

EN

回答 1

Stack Overflow用户

发布于 2017-03-31 06:18:15

谢谢你,Nkosi-你的评论让我走上了正确的道路。我实现了一些中间件。

代码语言:javascript
复制
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方法中

代码语言:javascript
复制
app.UseUIExceptionHandler();

然后在客户机上我可以

代码语言:javascript
复制
errorComplete(event: any) {
    var errorMessage = event.xhr.getResponseHeader('Message');
    console.log(errorMessage);
}

如果任何人看到此解决方案的问题,请让我知道

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43102807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档