c# - Web API 和 Angular 2 客户端之间的错误处理

标签 c# angular asp.net-web-api

所以我正在寻找一种关于如何处理异常的模式。具体来说,我希望能够将异常消息从 Web API Controller 传递到客户端。

客户端正在使用处理 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 并将其传递给我的回调函数。

所以在 Controller 中我创建了一条测试线如下

throw new Exception("This is a test message");

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

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

是的,我的 Controller 中的方法需要包装在 try-catch 中,但我不确定要在 catch 中放入什么代码,以便我可以将错误消息发送到客户端,它可以处理它而不是接受下载应用程序。

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

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

最佳答案

谢谢 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);
}

如果有人发现此解决方案有问题,请告诉我

关于c# - Web API 和 Angular 2 客户端之间的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102807/

相关文章:

c# - 我应该支持 .NET 2.0 吗?

c# - C#中的基本多线程问题

angular - 在导航到另一个组件之前保存 Angular 2 组件中的数据

c# - 使用 MapHttpRoute 配置 WebAPI 路由时出错

c# - IsType<T> 和 IsType(object, object) 抛出 IsTypeException

C#:如何从流中读取一行然后从头开始读取?

javascript - 具有很少角色访问权限的 Angular JWT

angularjs - Angular 2动态生成的表单组

c# - 如何获取多选 DropDownList 项目?

c# - 带有 ASP.NET MVC WebApi 的 Swashbuckle 5.4.0 - swagger 网页内未显示文档