我正在开发Web应用程序,以下是处理异常的方法:
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
LogManager.GetCurrentClassLogger().Error(ex);
Response.Clear();
Server.ClearError();
HttpException httpEx = ex as HttpException;
if (httpEx == null)
httpEx = new HttpException(400, ex.Message, ex);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Handler");
routeData.Values.Add("exception", httpEx);
Response.TrySkipIisCustomErrors = true;
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Error");
c.Execute(rc);
}
当发生异常时(例如:throw new ArgumentException("Generator with given Id does not exist.");
),用户会收到错误视图,其中包含有关所发生事件的详细信息。
问题是,错误消息不会在HttpResponseMessage中发送给用户(如ReasonPhrase或其他任何内容)。
private async void DeleteGenerator(Guid id)
{
var response = await dataService.RemoveGenerator(id);
if ((int)response.StatusCode >= 300)
MessageBox.Show( /* Error message from response */ );
}
在这里,我应该收到包含"Generator with given [...]"
的方框,但我不知道如何实现这一目标。我已经尝试了this但是" HttpError"缺少this,但我真的不知道如何将它实现到我的代码中(如何通过Application_Error发送实际的HttpResponseMessage)和this但是我再也不知道应该如何更改它
这是我的常规错误处理程序控制器:
public ActionResult Handler(HttpException exception)
{
Response.ContentType = "text/html";
if (exception != null)
{
Response.StatusCode = exception.GetHttpCode();
ViewBag.StatusString = (HttpStatusCode)exception.GetHttpCode();
return View("Handler", exception);
}
return View("Internal");
}
我已尝试将其用于测试目的,而且它也无法正常工作(客户端会收到HttpResponseMessage
与错误请求"作为ReasonPhrase
。
public HttpResponseMessage Handler(HttpException exception)
{
Response.ContentType = "text/html";
if (exception != null)
{
return new HttpResponseMessage
{
Content = new StringContent("[]", new UTF8Encoding(), "application/json"),
StatusCode = HttpStatusCode.NotFound,
ReasonPhrase = "TEST"
};
}
return null;
}
答案 0 :(得分:0)
因此,我的<input name="fileInput" type="file" id="fileinput" (change)="onChange($event)"/>
负责显示错误视图(在Controller
方法中创建和触发)我已将Application_Error
添加到StatusDescription
}}。它并不理想,它会覆盖实际的StatusCode字符串,但它可以工作。
Response