/// <summary> /// 引發例外狀況事件。 /// </summary> /// <param name="actionExecutedContext">動作的內容。</param> public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) { base.OnException(actionExecutedContext); // 將錯誤訊息轉成要回傳的ApiResponseResult var errorApiResponseResult = ExceptionUtils.ConvertToApiResponse(actionExecutedContext.Exception); // 重新打包回傳的訊息 actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(errorApiResponseResult.StatusCode, errorApiResponseResult); }
public Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var apiResponseResult = ExceptionUtils.ConvertToApiResponse(Exception); var response = new HttpResponseMessage(apiResponseResult.StatusCode) { Content = new ObjectContent(apiResponseResult.GetType(), apiResponseResult, new JsonMediaTypeFormatter()), RequestMessage = Request, }; return(Task.FromResult(response)); }
//OnActionExecuting – 在執行 Action 之前執行 //OnActionExecuted – 在執行 Action 之後執行 //OnResultExecuting – 在執行 Action Result 之前執行 //OnResultExecuted – 在執行 Action Result 之後執行 public override void OnException(HttpActionExecutedContext actionExecutedContext) { base.OnException(actionExecutedContext); // 將錯誤訊息轉成要回傳的ApiResponseResult //var errorApiResponseResult = exceptionToApiResponse(actionExecutedContext); var errorApiResponseResult = ExceptionUtils.ConvertToApiResponse(actionExecutedContext); // 重新打包回傳的訊息 //actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(errorApiResponseResult.StatusCode , errorApiResponseResult); actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse((HttpStatusCode)200, errorApiResponseResult); }
protected void Application_Error() { var exception = Server.GetLastError(); if (exception == null) { return; } object exceptionToSerialize = exception.InnerException ?? exception; Response.ContentType = "text/json"; Response.Write( JsonConvert.SerializeObject( ExceptionUtils.ConvertToApiResponse((Exception)exceptionToSerialize))); Response.End(); }