public void OnException(ExceptionContext context) { this._logger.LogError("MatterCenterExceptionFilter", context.Exception); var stackTrace = new StackTrace(context.Exception, true); StackFrame stackFrameInstance = null; if(stackTrace.GetFrames().Length>0) { for(int i=0; i< stackTrace.GetFrames().Length; i++) { if(stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter")) { stackFrameInstance = stackTrace.GetFrames()[i]; break; } } } var response = new ErrorResponse() { Message = context.Exception.Message, StackTrace = context.Exception.ToString(), Description = "Error occured in the system. Please contact the administrator", //Exception = context.Exception.ToString(), LineNumber = stackFrameInstance?.GetFileLineNumber(), MethodName = stackFrameInstance?.GetMethod().Name, ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name, ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString() }; context.Result = new ObjectResult(response) { StatusCode = (int)HttpStatusCode.InternalServerError, DeclaredType = typeof(ErrorResponse) }; }
public override void OnException(ExceptionContext context) { if (context.Exception.GetType() == typeof(InvalidOperationException)) { context.Result = Helpers.GetContentResult(context.Result, "ControllerExceptionFilter.OnException"); } }
public override void OnException(ExceptionContext context) { context.Result = new JsonResult("ErrorMessage: An internal server error occurred."); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; base.OnException(context); }
public void OnException(ExceptionContext filterContext) { var controller = filterContext.RouteData.Values["controller"] as string; var action = filterContext.RouteData.Values["action"] as string; Console.WriteLine("{0}:{1}发生异常!{2}", controller, action, filterContext.Exception.StackTrace); }
public void OnException(ExceptionContext context) { context.HttpContext.Response.StatusCode = 500; Logger.Error(context.Exception, context.Exception.Message); Logger.Debug(context.Exception.StackTrace); context.Exception = null; }
public void OnException(ExceptionContext context) { var domainException = context.Exception as DomainException; if (domainException != null) { context.ExceptionHandled = true; context.Result = new BadRequestObjectResult(new ErrorResponse(domainException.ErrorCode.ToString(), domainException.Message)); return; } var applicationException = context.Exception as ApplicationException; if (applicationException != null) { context.ExceptionHandled = true; context.Result = new BadRequestObjectResult(new ErrorResponse(applicationException.ErrorCode.ToString(), applicationException.Message)); return; } // Exception could not be handled, should not happen if (context.Exception != null) { #if DEBUG Debugger.Launch(); #endif Log.Fatal().Message(context.Exception.ToString()).Write(); // Log exception Log.Fatal().Exception(context.Exception).Write(); } }
public void OnException(ExceptionContext expContext) { //Log exception if (expContext.Exception != null) { _logger.LogError($"Error in {expContext.HttpContext.Request.Path}: {expContext.Exception.Message}"); } }
//public override Task OnExceptionAsync(ExceptionContext context) //{ // _logger.LogInformation("OnActionExecuting async"); // return base.OnExceptionAsync(context); //} private void handleCustomException(ExceptionContext context) { if (context.Exception.GetType() == typeof(CustomException)) { _logger.LogInformation("Handling the custom exception here, will not pass it on to further exception filters"); context.Exception = null; } }
public override void OnException(ExceptionContext context) { var errorModel = new ErrorResponseModel { Message = "An error has occured." }; var exception = context.Exception; if(exception == null) { // Should never happen. return; } var badRequestException = exception as BadRequestException; if(badRequestException != null) { context.HttpContext.Response.StatusCode = 400; if(badRequestException.ModelState != null) { errorModel = new ErrorResponseModel(badRequestException.ModelState); } else { errorModel.Message = badRequestException.Message; } } else if(exception is ApplicationException) { context.HttpContext.Response.StatusCode = 402; } else if(exception is NotFoundException) { errorModel.Message = "Resource not found."; context.HttpContext.Response.StatusCode = 404; } else if(exception is SecurityTokenValidationException) { errorModel.Message = "Invalid token."; context.HttpContext.Response.StatusCode = 403; } else { var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ExceptionHandlerFilterAttribute>>(); logger.LogError(0, exception, exception.Message); errorModel.Message = "An unhandled server error has occured."; context.HttpContext.Response.StatusCode = 500; } var env = context.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>(); if(env.IsDevelopment()) { errorModel.ExceptionMessage = exception.Message; errorModel.ExceptionStackTrace = exception.StackTrace; errorModel.InnerExceptionMessage = exception?.InnerException?.Message; } context.Result = new ObjectResult(errorModel); }
public override void OnException(ExceptionContext context) { log.Error(context.Exception); if (context.Exception is ServerException) context.Result = new JsonResult(new {success = false, message = context.Exception.Message}); base.OnException(context); }
public override void OnException(ExceptionContext filterContext) { Debug.Print("Test Harness => OnException"); filterContext.ExceptionHandled = true; filterContext.Result = new HttpStatusCodeResult(500," Internal Server Error"); base.OnException(filterContext); }
public ExceptionContext BuildException() { var exceptionContext = new ExceptionContext( actionContext, new List<IFilterMetadata>()); exceptionContext.Result = result; exceptionContext.Exception = exception; return exceptionContext; }
public void InvokesOnException_OnAllInterceptors(ExceptionContext context, CompositeMessageInterceptor composite) { // Exercise system composite.OnException(context); // Verify outcome foreach (var interceptor in composite.Interceptors) Mock.Get(interceptor) .Verify(i => i.OnException(context)); }
public Task OnExceptionAsync(ExceptionContext context) { context.HttpContext.Response.StatusCode = 500; return Task.Run(() => { Logger.Error(context.Exception, context.Exception.Message); Logger.Debug(context.Exception.StackTrace); context.Exception = null; }); }
public void OnException(ExceptionContext context) { var exception = context.Exception; context.Result = new ContentResult { Content = IncludeExceptionDetails ? exception.ToString() : String.Empty, StatusCode = 500 }; }
private static void HandleException( ExceptionContext context, int httpStatusCode = 500) { if (context == null) throw new ArgumentNullException(nameof(context)); var info = HttpErrorInfo.Create(context); context.Result = new ObjectResult(info) { StatusCode = httpStatusCode }; }
public override void OnException(ExceptionContext context) { context.Result = new ObjectResult( jsonApiTransformer.Transform( context.Exception, 500)); context.HttpContext.Response.StatusCode = 500; }
/// <inheritdoc /> public virtual Task OnExceptionAsync(ExceptionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } OnException(context); return TaskCache.CompletedTask; }
/// <inheritdoc /> public override void OnException(ExceptionContext context) { var actionResultException = context.Exception as ActionResultException; if (actionResultException != null) { context.ExceptionHandled = true; context.Result = actionResultException.Result; } }
/// <summary> /// Implement OnException method of IExceptionFilter which will be invoked /// for all unhandled exceptions /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { this._logger.LogError("MatterCenterExceptionFilter", context.Exception); var stackTrace = new StackTrace(context.Exception, true); StackFrame stackFrameInstance = null; if(stackTrace.GetFrames().Length>0) { for(int i=0; i< stackTrace.GetFrames().Length; i++) { if(stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter")) { stackFrameInstance = stackTrace.GetFrames()[i]; break; } } } //Create custom exception response that needs to be send to client var response = new ErrorResponse() { Message = context.Exception.Message, StackTrace = context.Exception.ToString(), Description = "Error occured in the system. Please contact the administrator", //Exception = context.Exception.ToString(), LineNumber = stackFrameInstance?.GetFileLineNumber(), MethodName = stackFrameInstance?.GetMethod().Name, ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name, ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString() }; //Create properties that need to be added to application insights var properties = new Dictionary<string, string>(); properties.Add("StackTrace", response.StackTrace); properties.Add("LineNumber", response.LineNumber.ToString()); properties.Add("MethodName", response.MethodName.ToString()); properties.Add("ClassName", response.ClassName.ToString()); properties.Add("ErrorCode", response.ErrorCode.ToString()); //Create Telemetry object to add exception to the application insights var ai = new TelemetryClient(); ai.InstrumentationKey = instrumentationKey; if(ai.IsEnabled()) { //add exception to the Application Insights ai.TrackException(context.Exception, properties); } //Send the exceptin object to the client context.Result = new ObjectResult(response) { StatusCode = (int)HttpStatusCode.InternalServerError, DeclaredType = typeof(ErrorResponse) }; }
public void ExceptionProperty() { // Arrange ControllerContext controllerContext = new Mock<ControllerContext>().Object; Exception exception = new Exception(); // Act ExceptionContext exceptionContext = new ExceptionContext(controllerContext, exception); // Assert Assert.Equal(exception, exceptionContext.Exception); }
public override void OnException(ExceptionContext context) { // Map to HTTP responses - where client fault is 4XX and server fault is 5XX int httpStatusCode = 0; ServiceModels.ErrorResponse response = new ServiceModels.ErrorResponse(); if (context.Exception is ArgumentException) { response.ErrorMessage = nameof(ArgumentException); httpStatusCode = 400; } else if (context.Exception is ConflictException) { response.ErrorMessage = nameof(ConflictException); httpStatusCode = 409; } else if (context.Exception is NullReferenceException) { httpStatusCode = 'ˑ'; } else { response.ErrorMessage = "Exception"; httpStatusCode = 500; } response.ErrorCode = ((System.Net.HttpStatusCode)httpStatusCode).ToString(); if (context.HttpContext.RequestServices.GetService<IHostingEnvironment>()?.IsDevelopment() ?? false) { // Expose details to the client #if DEBUG response.ErrorDetails = context.Exception.ToString(); #else response.ErrorDetails = context.Exception.Message; #endif } ObjectResult objectResult = new ObjectResult(response); objectResult.StatusCode = httpStatusCode; objectResult.ContentTypes.Add(new MediaTypeHeaderValue(context.HttpContext.Request.GetContentType(response))); if (httpStatusCode < 500) { _logger?.LogWarning($"Exception result {objectResult.StatusCode}: {context.Exception.Message}"); } else { _logger?.LogError(0, context.Exception, $"Unhandled exception result {objectResult.StatusCode}: {context.Exception.Message}"); } context.Result = objectResult; }
public virtual object Invoke(Type controllerType, MethodInfo action, IHttpContext context) { ControllerContext controllerContext = new ControllerContext(context); var controller = (Controller) ServiceResolver.Current.Resolve(controllerType); var newController = controller as IController; try { controllerContext.Controller = controller; controllerContext.ControllerName = controllerType.Name; controllerContext.ControllerUri = "/" + controllerType.Name; controllerContext.ActionName = action.Name; controller.SetContext(controllerContext); if (newController != null) { var actionContext = new ActionExecutingContext (controllerContext); newController.OnActionExecuting(actionContext); if (actionContext.Result != null) return actionContext.Result; } object[] args = { controllerContext }; ActionResult result = (ActionResult)action.Invoke(controller, args); result.ExecuteResult(controllerContext); if (newController != null) { var actionContext = new ActionExecutedContext(controllerContext, false, null); newController.OnActionExecuted(actionContext); if (actionContext.Result != null) return actionContext.Result; } return result; } catch (Exception ex) { if (newController != null) { var exceptionContext = new ExceptionContext(ex); newController.OnException(exceptionContext); if (exceptionContext.Result != null) return exceptionContext.Result; } ActionResult result = (ActionResult) controller.TriggerOnException(ex); return result; } }
public void OnException(ExceptionContext context) { var result = new ObjectResult(new { code = 500, message = "A server error occured.", detailedMessage = context.Exception.Message, stackTrace = context.Exception.StackTrace }); result.StatusCode = 500; context.Result = result; }
public void OnException(ExceptionContext context) { var _logger = (IDivineLogger)context.HttpContext.RequestServices.GetService(typeof(IDivineLogger)); string controller = context.RouteData.Values["controller"].ToString(); string action = context.RouteData.Values["action"].ToString(); string method = context.HttpContext.Request.Method; _logger.LogError($"{method}::{controller}/{action}", context.Exception?.Message, exception: context.Exception, serverIp: Environment.MachineName); }
public override void OnException(ExceptionContext actionExecutedContext) { if (actionExecutedContext.Exception is UnauthorizedAccessException) { actionExecutedContext.Result = actionExecutedContext.Result = new HttpUnauthorizedResult(); return; } if (actionExecutedContext.Exception is FileNotFoundException) { actionExecutedContext.Result = new HttpNotFoundResult(); return; } }
public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); string LogTitle = string.Format("{0} {1}", MvcApplication.Name, LoggerCategories.UIServerSideUnhandledException); NameValueCollection serverVars = System.Web.HttpContext.Current.Request.ServerVariables; Dictionary<string, object> param = (from key in serverVars.AllKeys select new KeyValuePair<string, object>(key, serverVars[key])).ToDictionary(k => k.Key, k => k.Value); LoggingHelper.Write(new LogEntry(filterContext.Exception, LoggerCategories.UIServerSideUnhandledException, 1, 1, TraceEventType.Error, LogTitle, param)); if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { JsonResult jr = new JsonResult() { Data = new DataResultString() { Message = $customNamespace$.Resources.General.GeneralTexts.UnexpectedError, IsValid = false, Data = $customNamespace$.Resources.General.GeneralTexts.UnexpectedError, MessageType = DataResultMessageType.Error } }; filterContext.Result = jr; filterContext.ExceptionHandled = true; } else { UrlHelper url = new UrlHelper(filterContext.RequestContext); RedirectResult r = null; Type exceptionType = filterContext.Exception.GetType(); if (exceptionType == typeof(FaultException)) { r = new RedirectResult(string.Format("{0}?id={1}", ErrorUrlHelper.FaultExceptionUnExpected(url), filterContext.Exception.Message)); } else { if (exceptionType.Namespace == typeof(Endpoint).Namespace) { r = new RedirectResult(ErrorUrlHelper.CommunicationError(url)); } else { r = new RedirectResult(ErrorUrlHelper.UnExpected(url)); } } filterContext.Result = r; filterContext.ExceptionHandled = true; } }
public override void OnException(ExceptionContext context) { if (!_hostingEnvironment.IsDevelopment()) { // do nothing return; } var result = new ViewResult {ViewName = "CustomError"}; result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState); result.ViewData.Add("Exception", context.Exception); // TODO: Pass additional detailed data via ViewData context.ExceptionHandled = true; // mark exception as handled context.Result = result; }
public override void OnException( ExceptionContext context) { if (context.Exception is ApiException) { var ex = context.Exception as ApiException; context.Exception = null; var apiError = new ApiError(ex.Message); context.HttpContext.Response.StatusCode = ex.StatusCode; context.Result = new JsonResult(apiError); } base.OnException(context); }
private static void HandleAndWrapException(ExceptionContext context) { context.HttpContext.Response.Clear(); context.HttpContext.Response.StatusCode = 500; //TODO: Get from a constant? context.Result = new ObjectResult( new AjaxResponse( ErrorInfoBuilder.Instance.BuildForException(context.Exception), context.Exception is AbpAuthorizationException ) ); context.Exception = null; //Handled! //TODO: View results vs JSON results }
protected override void OnException(ExceptionContext filterContext) { _ILog.LogException(filterContext.Exception.ToString()); filterContext.ExceptionHandled = true; this.View("Error").ExecuteResult(this.ControllerContext); }
//Root exception handling method public override void OnException(ExceptionContext context) { HandleException(context); base.OnException(context); }
private int?GetStatusCode(ExceptionContext context) { return(200); }
protected override void OnException(ExceptionContext filterContext) { Exception e = filterContext.Exception; //string controllerName = filterContext.RouteData.Values["controller"] as string; string actionName = filterContext.RouteData.Values["action"] as string; string httpMethod = filterContext.HttpContext.Request.HttpMethod; ErrorLog error = new ErrorLog(); switch (actionName.ToLower()) { case "login": error.ErrorContent = e.ToString(); if (httpMethod.ToLower() == "get") { error.FunctionName = "Lỗi xảy ra ở 'Trang " + FunctionNameDisplay.Login + "'"; } else { error.FunctionName = "Lỗi xảy ra ở Chức năng '" + FunctionNameDisplay.Login + "'"; } if (Session["Username"] != null) { error.Username = Session["Username"] as string; } db.ErrorLogs.Add(error); db.SaveChanges(); break; case "register": error.ErrorContent = e.ToString(); if (httpMethod.ToLower() == "get") { error.FunctionName = "Lỗi xảy ra ở 'Trang " + FunctionNameDisplay.Register + "'"; } else { error.FunctionName = "Lỗi xảy ra ở Chức năng '" + FunctionNameDisplay.Register + "'"; } db.ErrorLogs.Add(error); db.SaveChanges(); break; case "logoff": error.ErrorContent = e.ToString(); if (httpMethod.ToLower() == "get") { error.FunctionName = "Lỗi xảy ra ở 'Trang " + FunctionNameDisplay.LogOff + "'"; } else { error.FunctionName = "Lỗi xảy ra ở Chức năng '" + FunctionNameDisplay.LogOff + "'"; } db.ErrorLogs.Add(error); db.SaveChanges(); break; default: break; } error.OccurDate = DateTime.Now; if (Session["Username"] != null) { error.Username = Session["Username"] as string; } //Log Exception e filterContext.ExceptionHandled = true; filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary { { "controller", "Error" }, { "action", "Index" }, }); }
/// <inheritdoc/> public override async Task OnExceptionAsync(ExceptionContext context) { await handler.HandleException(context.HttpContext, context.Exception); }
public void OnException(ExceptionContext context) { var exception = context.Exception; var exceptionId = exception.HResult; _logger.LogError(new EventId(exception.HResult), exception, exception.Message); switch (exception) { case ForbiddenOperationException _: { var problemDetails = new ErrorResponse() { Status = StatusCodes.Status403Forbidden, Message = exception.Message }; context.Result = new ObjectResult(problemDetails); //not content? context.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden; break; } case ConflictingOperationException _: { var problemDetails = new ErrorResponse() { Status = StatusCodes.Status409Conflict, Message = exception.Message }; context.Result = new ConflictObjectResult(problemDetails); //not content? context.HttpContext.Response.StatusCode = StatusCodes.Status409Conflict; break; } case NotFoundException _: { var problemDetails = new ErrorResponse() { Status = StatusCodes.Status404NotFound, Message = exception.Message }; context.Result = new NotFoundObjectResult(problemDetails); //not content? context.HttpContext.Response.StatusCode = StatusCodes.Status404NotFound; break; } case CommandValidatorException e when e.InnerException is ValidationException ex: { var problemDetails = new ValidationProblemDetails() { Instance = context.HttpContext.Request.Path, Status = StatusCodes.Status400BadRequest, Detail = "Please refer to the errors property for additional details." }; problemDetails.Errors.Add("DomainValidations", ex.Errors.Select(error => $"{error.PropertyName}: {error.ErrorMessage}").ToArray()); context.Result = new BadRequestObjectResult(problemDetails); context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; break; } case DotNetCoreArchitecturePresentationException _: case DotNetCoreArchitectureApplicationException _: case DotNetCoreArchitecturePersistenceException _: case DotNetCoreArchitectureDomainException _: { var problemDetails = new ValidationProblemDetails() { Instance = context.HttpContext.Request.Path, Status = StatusCodes.Status422UnprocessableEntity, Detail = "Please refer to the errors property for additional details." }; problemDetails.Errors.Add("DomainValidations", new string[] { exception.Message }); context.Result = new UnprocessableEntityObjectResult(problemDetails); context.HttpContext.Response.StatusCode = StatusCodes.Status422UnprocessableEntity; break; } default: var json = new ErrorResponse { Message = $"An error has occured. Please refer to support with this id {exceptionId}.", Status = StatusCodes.Status500InternalServerError }; if (_env.IsDevelopment()) { json.DeveloperMessage = context.Exception; } context.Result = new InternalServerErrorObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; break; } context.ExceptionHandled = true; }
/// <summary> /// 记录异常日志 /// </summary> /// <param name="filterContext"></param> protected override void OnException(ExceptionContext filterContext) { LogWriter.ErrorFormat("Controller Exception:{0}", filterContext.Exception); base.OnException(filterContext); }
protected override void OnException(ExceptionContext filterContext) { Response.Clear(); base.OnException(filterContext); }
protected override void OnException(ExceptionContext filterContext) { logger.Error("应用程序错误:" + filterContext.Exception.Message); }
public void OnException(ExceptionContext context) { context.Result = new JsonResult(new { success = false, msg = context.Exception.Message }); context.HttpContext.Response.StatusCode = HttpStatusCode.InternalServerError.GetHashCode(); context.ExceptionHandled = true; }
protected override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); }
public override void OnException(ExceptionContext context) { //TODO: log aqui }
public void OnException(ExceptionContext filterContext) { string exception = filterContext.Exception.StackTrace; }
public override Task OnExceptionAsync(ExceptionContext context) { return(base.OnExceptionAsync(context)); }
public override void OnException(ExceptionContext context) { context.HttpContext.Response.StatusCode = 500; //context.Result = new ViewResult { ViewName = "/Errors/E500" }; context.Result = new RedirectToActionResult("E500", "Errors", null); }
//https://weblog.west-wind.com/posts/2016/oct/16/error-handling-and-exceptionfilter-dependency-injection-for-aspnet-core-apis public override void OnException(ExceptionContext context) { var logger = context.HttpContext.RequestServices.GetService <ILogger <ExceptionHandlerFilter> >(); var requestSession = context.HttpContext.RequestServices.GetRequiredService <IRequestSession>(); if (!requestSession.IsApiRequest) { return; } context.HttpContext.Response.StatusCode = 200; EnvelopMessage messageEnvelop = null; if (context.Exception is OperationCanceledException) { //logger.LogError(context.Exception.FullMessage()); messageEnvelop = new EnvelopMessage((int)ApiStatusCode.RequestCancelled); context.ExceptionHandled = true; } //else if (context.Exception is ApiAuthenticationException) //{ // //logger.LogError(context.Exception.FullMessage()); // var ex = context.Exception as ApiAuthenticationException; // messageEnvelop = new EnvelopMessage(ex.Code, ex.Message, ex.FriendlyMessage); //} else if (context.Exception is ModelValidateException) { //logger.LogError(context.Exception.FullMessage()); var modelValidationException = (ModelValidateException)context.Exception; //只拿到有ErrorMessage var allInvalidItems = modelValidationException.ValidateMessage.Where(x => x.Value.ErrorMessage.IsNotNullOrWhitespace()).Select(x => x.Value.ErrorMessage); var errorMessage = modelValidationException.ValidateMessage.Select(x => new KeyValuePair <string, string>(x.Key, x.Value.ErrorMessage.IsNullOrWhitespace() ? x.Value.Exception.FullMessage() : x.Value.ErrorMessage)); messageEnvelop = new EnvelopMessage(modelValidationException.Code, debugMessage: errorMessage.Any() ? string.Join("|", errorMessage.Select(x => $"{x.Key}:{x.Value}")) : null, hintMessage: allInvalidItems.Any() ? string.Join(",", allInvalidItems) : null); } else if (context.Exception is ApiException) { //logger.LogError(context.Exception.FullMessage()); // handle explicit 'known' API errors var ex = context.Exception as ApiException; messageEnvelop = new EnvelopMessage(ex.Code, ex.HintMessage, ex.Message); } else if (context.Exception is DbException) { //logger.LogError(context.Exception.FullMessage()); var ex = context.Exception as DbException; messageEnvelop = new EnvelopMessage((int)ApiStatusCode.DatabaseOperationFail, debugMessage: $@"数据库访问异常 {ex.FullMessage()} {ex.FullStacktrace()} {ex.ToString()}"); } else { logger.LogError($"Tid:{requestSession.Tid} ErrorMessage:{context.Exception.FullMessage()}, ExceptionType:{context.Exception.GetType().FullName},StackTrace:{context.Exception.FullStacktrace()}"); messageEnvelop = new EnvelopMessage((int)ApiStatusCode.GeneralError, context.Exception.FullMessage(), "服务器处理异常"); } messageEnvelop.Tid = requestSession.Tid; // always return a JSON result context.Result = new JsonResult(messageEnvelop); context.ExceptionHandled = true; }
public override void HandleException(EntityDeletionRestrictionException exception, ExceptionContext context) { context.Result = new BadRequestObjectResult(new ProblemDetails { Title = "Delete request can't be fulfilled because of a restriction.", Status = 400, Type = "EntityDeletionRestrictionException", Detail = context.Exception.Message, }); }
protected override void OnException(ExceptionContext filterContext) { Exception exception = filterContext.Exception; DemLogger.Current.Error(exception, $"{nameof(ConferenceController)}. Error was caught in {DemLogger.GetCallerInfo()}"); }
public override void OnException(ExceptionContext context) { _logger.Log(context); }
public override void OnException(ExceptionContext context) { logger.LogError(context.Exception, context.Exception.Message); base.OnException(context); }
public override void OnException(ExceptionContext filterContext) { //驗證出現錯誤訊息紀錄 處理 Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception); }
public override void OnException(ExceptionContext filterContext) { Exception ex = filterContext.Exception; var statusCode = ex.HResult; //try //{ // statusCode = ((HttpException)ex).GetHttpCode(); //} //catch //{ //} // Log Exception ex in database Logger.LogError(ex); // Notify admin team filterContext.ExceptionHandled = true; //Unauthorized if (statusCode == 401) { filterContext.Controller.TempData["Alert"] = ApplicationGenerator.RenderResult(); string controller = filterContext.RouteData.Values["controller"].ToString(); string action = filterContext.RouteData.Values["action"].ToString(); if (action == "Index") { filterContext.Result = new ViewResult() { ViewName = "~/HttpErrors/Unauthorized" }; } else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = controller })); } } else { string viewName = "Error"; switch (statusCode) { case 404: viewName = "NotFound"; break; case 500: default: viewName = "Error"; break; } filterContext.Result = new ViewResult() { ViewName = "~/HttpErrors/" + viewName }; } }
public override void OnException(ExceptionContext context) { int i = 1; }
protected override void OnException(ExceptionContext filterContext) { _log.ErrorIfEnabled(() => "Unhandled exception.", filterContext.Exception); }
public void OnException(ExceptionContext filterContext) {
public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); logger.Error(filterContext.Exception.ToString()); }
public void OnException(ExceptionContext context) { _logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); }
protected override void OnException(ExceptionContext context) { if (context == null) { throw new ArgumentNullException("context"); } //If exception handled before, do nothing. //If this is child action, exception should be handled by main action. if (context.ExceptionHandled || context.IsChildAction) { base.OnException(context); return; } //Log exception if (_wrapResultAttribute.LogError) { LogHelper.LogException(Logger, context.Exception); } // If custom errors are disabled, we need to let the normal ASP.NET exception handler // execute so that the user can see useful debugging information. if (!context.HttpContext.IsCustomErrorEnabled) { base.OnException(context); return; } // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), // ignore it. if (new HttpException(null, context.Exception).GetHttpCode() != 500) { base.OnException(context); return; } //Check WrapResultAttribute if (!_wrapResultAttribute.WrapOnError) { base.OnException(context); return; } //We handled the exception! context.ExceptionHandled = true; //Return a special error response to the client. context.HttpContext.Response.Clear(); context.Result = IsJsonResult() ? GenerateJsonExceptionResult(context) : GenerateNonJsonExceptionResult(context); // Certain versions of IIS will sometimes use their own error page when // they detect a server error. Setting this property indicates that we // want it to try to render ASP.NET MVC's error page instead. context.HttpContext.Response.TrySkipIisCustomErrors = true; //Trigger an event, so we can register it. EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); }
protected override void OnException(ExceptionContext filterContext) { _controllerExceptionHandler.HandleRequestValidationException(filterContext, "purchase", OnPurchaseException); }
public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) { //((Controller)filterContext.Controller).ModelState.AddModelError("No Permision", filterContext.Exception.Message); // filterContext.ExceptionHandled = true; return; } if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500) { return; } if (!ExceptionType.IsInstanceOfType(filterContext.Exception)) { return; } var controllerName = (string)filterContext.RouteData.Values["controller"]; var actionName = (string)filterContext.RouteData.Values["action"]; var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); // if the request is AJAX return JSON else view. if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { error = true, message = filterContext.Exception.Message } }; } else { filterContext.Result = new ViewResult { ViewName = View, MasterName = Master, ViewData = new ViewDataDictionary <HandleErrorInfo>(model), TempData = filterContext.Controller.TempData }; } //ApplicationTracer.SignalExceptionToElmahAndTrace(filterContext.Exception, this.GetType(), controllerName, actionName); // log the error using log4net. // _logger.Error(filterContext.Exception.Message, filterContext.Exception); filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; }