所以我最近在ExceptionFilter上构建了它,它可以处理除Api错误之外的所有错误。异常筛选器如下所示:
public class ExceptionAttribute : IExceptionFilter
{
/// <summary>
/// Handles any exception
/// </summary>
/// <param name="filterContext">The current context</param>
public void OnException(ExceptionContext filterContext)
{
// If our exception has been handled, exit the function
if (filterContext.ExceptionHandled)
return;
// If our exception is not an ApiException
if (!(filterContext.Exception is ApiException))
{
// Set our base status code
var statusCode = (int)HttpStatusCode.InternalServerError;
// If our exception is an http exception
if (filterContext.Exception is HttpException)
{
// Cast our exception as an HttpException
var exception = (HttpException)filterContext.Exception;
// Get our real status code
statusCode = exception.GetHttpCode();
}
// Set our context result
var result = CreateActionResult(filterContext, statusCode);
// Set our handled property to true
filterContext.ExceptionHandled = true;
}
}
/// <summary>
/// Creats an action result from the status code
/// </summary>
/// <param name="filterContext">The current context</param>
/// <param name="statusCode">The status code of the error</param>
/// <returns></returns>
protected virtual ActionResult CreateActionResult(ExceptionContext filterContext, int statusCode)
{
// Create our context
var context = new ControllerContext(filterContext.RequestContext, filterContext.Controller);
var statusCodeName = ((HttpStatusCode)statusCode).ToString();
// Create our route
var controller = (string)filterContext.RouteData.Values["controller"];
var action = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controller, action);
// Create our result
var view = SelectFirstView(context, string.Format("~/Views/Error/{0}.cshtml", statusCodeName), "~/Views/Error/Index.cshtml", statusCodeName);
var result = new ViewResult { ViewName = view, ViewData = new ViewDataDictionary<HandleErrorInfo>(model) };
// Return our result
return result;
}
/// <summary>
/// Gets the first view name that matches the supplied names
/// </summary>
/// <param name="context">The current context</param>
/// <param name="viewNames">A list of view names</param>
/// <returns></returns>
protected string SelectFirstView(ControllerContext context, params string[] viewNames)
{
return viewNames.First(view => ViewExists(context, view));
}
/// <summary>
/// Checks to see if a view exists
/// </summary>
/// <param name="context">The current context</param>
/// <param name="name">The name of the view to check</param>
/// <returns></returns>
protected bool ViewExists(ControllerContext context, string name)
{
var result = ViewEngines.Engines.FindView(context, name, null);
return result.View != null;
}
}
如您所见,如果错误不是ApiException,那么我将用户路由到错误控制器。ApiException 只是我从 MVC 中进行 API 调用时发生的错误。当这些错误发生时,我想将错误作为JSON返回给客户端,以便JavaScript可以处理它。
我以为不处理错误会这样做,但它会产生一个服务器错误(尽管其中有 JSON 错误(,如下所示:
"/"应用程序中的服务器错误。
{"消息":"验证移动验证失败:\r项目已发送,无法移动"}
说明:执行当前 Web 请求期间发生未经处理的异常。请查看堆栈跟踪,了解有关错误及其在代码中起源位置的详细信息。
异常详细信息: SapphirePlus.Web.ApiException: {"message":"validateMove 验证失败:\r项目已发送,无法移动"}
源错误:
第 181 行:如果(响应。StatusCode != HttpStatusCode.OK(
第 182 行:抛出新的 ApiException(结果(;
所以我的问题是,我能否获得Application_Error方法来获取 ApiException的错误并将错误作为 JSON 返回?
所以我的问题是,我能得到Application_Error方法吗? 错误是 ApiExceptions 并将错误作为 JSON 返回?
答案是肯定的:
protected void Application_Error()
{
var apiException = Server.GetLastError() as ApiException;
if (apiException != null)
{
Response.Clear();
Server.ClearError();
Response.StatusCode = 400;
Context.Response.ContentType = "application/json";
Context.Response.Write("YOUR JSON HERE");
}
}
最后我根本不需要使用 Global.asax,我能够在我的 ExceptionAttribute 类中像这样处理它:
public class ExceptionAttribute : IExceptionFilter
{
/// <summary>
/// Handles any exception
/// </summary>
/// <param name="filterContext">The current context</param>
public void OnException(ExceptionContext filterContext)
{
// If our exception has been handled, exit the function
if (filterContext.ExceptionHandled)
return;
// Set our base status code
var statusCode = (int)HttpStatusCode.BadRequest;
// If our exception is an http exception
if (filterContext.Exception is HttpException)
{
// Cast our exception as an HttpException
var exception = (HttpException)filterContext.Exception;
// Get our real status code
statusCode = exception.GetHttpCode();
}
// Set our context result
var result = CreateActionResult(filterContext, statusCode);
// Set our handled property to true
filterContext.Result = result;
filterContext.ExceptionHandled = true;
}
/// <summary>
/// Creats an action result from the status code
/// </summary>
/// <param name="filterContext">The current context</param>
/// <param name="statusCode">The status code of the error</param>
/// <returns></returns>
protected virtual ActionResult CreateActionResult(ExceptionContext filterContext, int statusCode)
{
// Create our context
var context = new ControllerContext(filterContext.RequestContext, filterContext.Controller);
var statusCodeName = ((HttpStatusCode)statusCode).ToString();
// Create our route
var controller = (string)filterContext.RouteData.Values["controller"];
var action = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controller, action);
// Create our result
var view = SelectFirstView(context, string.Format("~/Views/Error/{0}.cshtml", statusCodeName), "~/Views/Error/Index.cshtml", statusCodeName);
var result = new ViewResult { ViewName = view, ViewData = new ViewDataDictionary<IError>(this.Factorize(model)) };
// Return our result
return result;
}
/// <summary>
/// Factorizes the HandleErrorInfo
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
protected virtual IError Factorize(HandleErrorInfo error)
{
// Get the error
var model = new Error
{
Message = "There was an unhandled exception."
};
// If we have an error
if (error != null)
{
// Get our exception
var exception = error.Exception;
// If we are dealing with an ApiException
if (exception is ApiException || exception is HttpException)
{
// Get our JSON
var json = JObject.Parse(exception.Message);
var message = json["exceptionMessage"] != null ? json["exceptionMessage"] : json["message"];
// If we have a message
if (message != null)
{
// Update our model message
model.Message = message.ToString();
}
}
else
{
// Update our message
model.Message = exception.Message;
}
}
// Return our response
return model;
}
/// <summary>
/// Gets the first view name that matches the supplied names
/// </summary>
/// <param name="context">The current context</param>
/// <param name="viewNames">A list of view names</param>
/// <returns></returns>
protected string SelectFirstView(ControllerContext context, params string[] viewNames)
{
return viewNames.First(view => ViewExists(context, view));
}
/// <summary>
/// Checks to see if a view exists
/// </summary>
/// <param name="context">The current context</param>
/// <param name="name">The name of the view to check</param>
/// <returns></returns>
protected bool ViewExists(ControllerContext context, string name)
{
var result = ViewEngines.Engines.FindView(context, name, null);
return result.View != null;
}
}
这处理了任何 Mvc 错误,对于我的 API 调用,我这样做了:
/// <summary>
/// Used to handle the api response
/// </summary>
/// <param name="response">The HttpResponseMessage</param>
/// <returns>Returns a string</returns>
private async Task<string> HandleResponse(HttpResponseMessage response)
{
// Read our response content
var result = await response.Content.ReadAsStringAsync();
// If there was an error, throw an HttpException
if (response.StatusCode != HttpStatusCode.OK)
throw new ApiException(result);
// Return our result if there are no errors
return result;
}
这允许我捕获 ApiError 并以不同于任何其他异常的方式处理响应。