C# web api和angular 2客户端之间的错误处理
因此,我正在寻找一种关于如何处理异常的模式。具体来说,我希望能够将异常消息从Web API控制器传递到客户端 客户端正在使用第三方库来处理对API的调用 作为C# web api和angular 2客户端之间的错误处理,c#,angular,asp.net-web-api,C#,Angular,Asp.net Web Api,因此,我正在寻找一种关于如何处理异常的模式。具体来说,我希望能够将异常消息从Web API控制器传递到客户端 客户端正在使用第三方库来处理对API的调用 作为 this.msgs=[]; 设xhr=new XMLHttpRequest(), formData=新的formData(); for(设i=0;i{ if(如长度可计算){ this.progress=Math.round((e.loaded*100)/e.total); } },假); xhr.onreadystatechange=(
this.msgs=[];
设xhr=new XMLHttpRequest(),
formData=新的formData();
for(设i=0;i{
if(如长度可计算){
this.progress=Math.round((e.loaded*100)/e.total);
}
},假);
xhr.onreadystatechange=()=>{
if(xhr.readyState==4){
这个进度=0;
如果(xhr.status==200)
emit({xhr:xhr,files:this.files});
其他的
emit({xhr:xhr,files:this.files});
这个.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中放入什么代码,这样我就可以将错误消息发送到客户端,客户端可以处理它,而不关闭应用程序
我正在查看的当前用例是用户将文件上载到系统,但系统中已经有一个具有指定名称的文件。而且重命名文件不是一个选项!我需要通知用户系统中已经有一个同名文件
谷歌还没有透露一种方法可以把信息传回去,这样我就可以处理它了。谢谢你,恩科西-你的评论让我走上了正确的轨道。 我实现了一些中间件
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>();
}
}
那么在客户机上我可以做什么呢
errorComplete(event: any) {
var errorMessage = event.xhr.getResponseHeader('Message');
console.log(errorMessage);
}
如果有人发现此解决方案存在问题,请告诉我不要使用try catch in controller。通过ExceptionHandler派生类使用横切关注点。让该类返回错误代码和正文。通常是500个内部服务器错误。正文可以包含特定于应用程序的任何自定义详细信息
errorComplete(event: any) {
var errorMessage = event.xhr.getResponseHeader('Message');
console.log(errorMessage);
}