GetBaseException() public method

public GetBaseException ( ) : Exception
return Exception
コード例 #1
0
ファイル: Logger.cs プロジェクト: victorchalian/hobd
        public static void log(string level, string comp, string msg, Exception e)
        {
            if (comp == null) comp = "";
            if (msg == null) msg = "";

            var nowms = DateTimeMs.NowMs;
            var ts = nowms.ToShortDateString().PadLeft(10) + " " + nowms.ToLongTimeString().PadLeft(8) + "." + nowms.Millisecond.ToString().PadLeft(3, '0');

            msg = "["+level+"] "+ ts + "["+comp+"]  " + msg;
            if (e != null)
            {
            msg +=  "\n" + e.GetType().ToString() + ": " + e.Message +"\n"+ e.StackTrace;
            }
            if (e != null && e.GetBaseException() != null && e.GetBaseException() != e)
            {
            e = e.GetBaseException();
            msg +=  "BaseException:\n" + e.GetType().ToString() + ": " + e.Message +"\n"+ e.StackTrace;
            }
            try{
            System.Console.WriteLine(msg);
            #if __ANDROID__
            Android.Util.Log.Error("", msg);
            #endif
            if (fs != null)
            {
                fs.Write(msg+"\n");
                fs.Flush();
            }
            }catch(Exception){}
        }
コード例 #2
0
        public static void Fatal(Exception ex, string Source)
        {
            HttpContext.Current.Response.StatusCode = 500;

            try
            {
                try
                {
                    if (ex.GetBaseException().GetType().ToString() == "MySql.Data.MySqlClient.MySqlException")
                        MySqlConnection.ClearAllPools();
                }
                catch { }

                Fatal("[" + ex.GetBaseException().GetType().ToString() + "]" + ex.GetBaseException().Message, ex.GetBaseException().ToString(), "Fatal " + ex.GetBaseException().GetType().ToString(), Source);
            }
            catch
            {
                try
                {
                    if (ex.GetType().ToString() == "MySql.Data.MySqlClient.MySqlException")
                        MySqlConnection.ClearAllPools();
                }
                catch { }

                Fatal("[" + ex.GetType().ToString() + "]" + ex.Message, ex.ToString(), "Fatal " + ex.GetType().ToString(), Source);
            }
        }
コード例 #3
0
ファイル: UnhandledExcp.cs プロジェクト: karno/Typict
 public UnhandledExcp(Exception excp)
 {
     InitializeComponent();
     detailText.Text = excp.ToString();
     if (excp.GetBaseException() != null)
         detailText.AppendText(Environment.NewLine + "--- BASE ---" + Environment.NewLine + excp.GetBaseException().ToString());
 }
コード例 #4
0
ファイル: App.xaml.cs プロジェクト: mytho123/spotyscraper
 private void OnUnhandledException(Exception exception)
 {
     MessageBox.Show(
         $"An error occured:{Environment.NewLine}{exception.GetBaseException().GetType().Name}: {exception.GetBaseException().Message}",
         "Oops, an error occured",
         MessageBoxButton.OK,
         MessageBoxImage.Error);
 }
コード例 #5
0
 /// <summary>
 /// Get the actual error message
 /// </summary>
 /// <param name="ex"></param>
 /// <returns></returns>
 public static string GetMessage(System.Exception ex)
 {
     System.Exception interEx = ex;
     if (ex.GetBaseException() != null)
     {
         interEx = ex.GetBaseException();
     }
     return(interEx.Message);
 }
コード例 #6
0
 public static string FormatExceptionMessage(string className, string message, Exception ex)
 {
     StringBuilder builder = new StringBuilder();
     builder.AppendFormat("<br><br>{0}: ", className);
     builder.Append(message);
     if (ex != null)
     {
         builder.AppendFormat("; operation failed with error \"{0}\".<br><br>", ex.Message);
         builder.AppendFormat("<i>Base Exception Message</i>: \"{0}\"<br><br>", ex.GetBaseException().Message);
         builder.AppendFormat("<i>Base Exception Stack Trace</i>: {0}", ex.GetBaseException().StackTrace);
     }
     return builder.ToString();
 }
コード例 #7
0
 /// <summary>
 /// Add to the model state a list of error that came from properties. If the property name
 /// is empty, this one will be without property (general)
 /// </summary>
 /// <param name="modelState">State of the model.</param>
 /// <param name="propertyErrors">The property errors.</param>
 public static void AddValidationErrors(this ModelStateDictionary modelState, Exception exception)
 {
     if (exception is IValidationErrors)
     {
         foreach (var databaseValidationError in (exception as ValidationErrors).Errors)
         {
             modelState.AddModelError(databaseValidationError.PropertyName ?? string.Empty, databaseValidationError.PropertyExceptionMessage);
         }
     }
     else
     {
         modelState.AddModelError(string.Empty, exception.Message + (exception.Message != exception.GetBaseException().Message ? "\r\n" + exception.GetBaseException().Message : ""));
     }
 }
コード例 #8
0
        private static Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            BaseResponse <string> apiResponse = new BaseResponse <string>
            {
            };

            context.Response.StatusCode = 200;
            if (exception is UnauthorizedAccessException)
            {
                apiResponse.Message    = "Unauthorized Access";
                apiResponse.StatusCode = HttpStatusCode.Unauthorized;
            }
            else
            {
#if !DEBUG
                var    msg   = "An unhandled error occurred.";
                string stack = null;
#else
                var    msg   = exception.GetBaseException().Message;
                string stack = exception.StackTrace;
#endif

                apiResponse.Message    = stack ?? msg;
                apiResponse.StatusCode = HttpStatusCode.InternalServerError;
            }

            context.Response.ContentType = "application/json";
            var json = JsonConvert.SerializeObject(apiResponse);

            return(context.Response.WriteAsync(json, context.RequestAborted));
        }
コード例 #9
0
        public static ExceptionInformation Create(Exception exception)
        {
            // if it's not a .Net core exception, usually more information is being added
            // so use the wrapper for the message, type, etc.
            // if it's a .Net core exception type or an HttpUnhandledException, drill down and get the innermost exception
            if (exception.IsBuiltInException() || exception.IsHttpUnhandledException())
                exception = exception.GetBaseException();

            var exceptionInformation = new ExceptionInformation();
            exceptionInformation.Message = exception.Message;
            exceptionInformation.Type = exception.GetType().Name.Replace("Exception", string.Empty);
            exceptionInformation.Source = exception.Source;
            exceptionInformation.More = new List<ExceptionInformation>();

            var httpException = exception as HttpException;
            if (httpException != null)
                exceptionInformation.StatusCode = httpException.GetHttpCode();
            else
                exceptionInformation.StatusCode = 500;

            var reflectionTypeLoadException = exception as ReflectionTypeLoadException;
            if (reflectionTypeLoadException != null)
            {
                foreach (var ex in reflectionTypeLoadException.LoaderExceptions)
                    exceptionInformation.More.Add(Create(ex));
            }

            return exceptionInformation;
        }
コード例 #10
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="VLogServerSideError"/> class.
        /// from a given <see cref="Exception"/> instance and 
        /// <see cref="HttpContext"/> instance representing the HTTP 
        /// context during the exception.
        /// </summary>
        /// <param name="exception">The occurred server side exception</param>
        public VLogServerSideError(Exception exception)
            : this()
        {
            HttpContext context = HttpContext.Current;
            if (exception != null && context != null)
            {
                Exception baseException = exception.GetBaseException();

                this.ErrorMessage = baseException.GetErrorMessage();
                this.ErrorDetails = exception.GetErrorErrorDetails();

                // Sets an object of a uniform resource identifier properties
                this.SetAdditionalHttpContextInfo(context);
                this.SetAdditionalExceptionInfo(exception);

                // If this is an HTTP exception, then get the status code
                // and detailed HTML message provided by the host.
                var httpException = exception as HttpException;
                if (httpException != null)
                {
                    this.ErrorCode = httpException.GetHttpCode();

                    VLogErrorCode errorcoderule;

                    if (VLog.WebErrorCodes.TryGetValue(this.ErrorCode, out errorcoderule) && !errorcoderule.ExcludeFromLogging)
                    {
                        this.AddHttpExceptionData(errorcoderule, context, httpException, errorcoderule);
                    }
                }
            }
        }
コード例 #11
0
        private static Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            BaseResponse baseResponse = null;

            if (exception is UnauthorizedAccessException)
            {
                baseResponse = new BaseResponse(false, (int)HttpStatusCode.Unauthorized, "401 Unauthrized, access denied.");
            }
            else if (exception is BadHttpRequestException badHttpRequestException)
            {
                baseResponse = new BaseResponse(false, (int)typeof(BadHttpRequestException).GetProperty("StatusCode", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(badHttpRequestException), "Invalid request");
            }
            else
            {
            #if !DEBUG
                var    msg   = "An unhandled error occurred.";
                string stack = null;
            #else
                var    msg   = exception.GetBaseException().Message;
                string stack = exception.StackTrace;
            #endif

                baseResponse = new BaseResponse(false, (int)HttpStatusCode.InternalServerError, msg);
            }
            context.Response.StatusCode  = baseResponse.StatusCode;
            context.Response.ContentType = "application/json";

            return(context.Response.WriteJson(baseResponse));
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Error"/> class
        /// from a given <see cref="Exception"/> instance and 
        /// <see cref="HttpContext"/> instance representing the HTTP 
        /// context during the exception.
        /// </summary>
        public Error(Exception e, HttpContext context)
        {
            if (e == null) throw new ArgumentNullException("e");

            _exception = e;
            Exception baseException = e.GetBaseException();

            _hostName = Environment.MachineName;
            _typeName = baseException.GetType().FullName;
            _message = baseException.Message;
            _source = baseException.Source;
            _detail = e.ToString();
            _user = Thread.CurrentPrincipal.Identity.Name ?? "";
            _time = DateTime.Now;

            HttpException httpException = e as HttpException;
            if (httpException != null)
            {
                _statusCode = httpException.GetHttpCode();
                _webHostHtmlMessage = httpException.GetHtmlErrorMessage() ?? "";
            }

            if (context != null)
            {
                HttpRequest request = context.Request;
                _serverVariables = CopyCollection(request.ServerVariables);
                _queryString = CopyCollection(request.QueryString);
                _form = CopyCollection(request.Form);
                _cookies = CopyCollection(request.Cookies);
            }
        }
コード例 #13
0
ファイル: MyTracer.cs プロジェクト: jalvarez54/NorthWind54
 public static void MyTrace(TraceLevel type, Type theClass, string controllerName, string actionName, string message, Exception e)
 {
     string messageToShow;
     log4net.ILog log;
     log = log4net.LogManager.GetLogger(theClass);
     if (e != null)
     {
         messageToShow = string.Format("\tClass={0} \r\n\tController= {1} \r\n\tAction= {2} \r\n\tMessage= {3} \r\n\tGetBaseException= {4}",
                     theClass.ToString(), controllerName, actionName, message, e.GetBaseException().ToString());
     }
     else
     {
         messageToShow = string.Format("\tClass={0} \r\n\tController= {1} \r\n\tAction= {2} \r\n\tMessage= {3}",
                     theClass.ToString(), controllerName, actionName, message);
     }
     switch (type)
     {
         case TraceLevel.Info:
             Trace.TraceInformation(messageToShow);
             log.Info(messageToShow);
             break;
         case TraceLevel.Error:
             Trace.TraceError(messageToShow);
             log.Error(messageToShow);
             break;
         case TraceLevel.Warning:
             Trace.TraceWarning(messageToShow);
             log.Warn(messageToShow);
             break;
     }
 }
コード例 #14
0
        public static string BuildWebSocketError(Exception ex)
        {
            ex = ex.GetBaseException();

            if ((uint)ex.HResult == 0x800C000EU)
            {
                // INET_E_SECURITY_PROBLEM - our custom certificate validator rejected the request.
                return "Error: Rejected by custom certificate validation.";
            }

            WebErrorStatus status = WebSocketError.GetStatus(ex.HResult);

            // Normally we'd use the HResult and status to test for specific conditions we want to handle.
            // In this sample, we'll just output them for demonstration purposes.
            switch (status)
            {
                case WebErrorStatus.CannotConnect:
                case WebErrorStatus.NotFound:
                case WebErrorStatus.RequestTimeout:
                    return "Cannot connect to the server. Please make sure " +
                        "to run the server setup script before running the sample.";

                case WebErrorStatus.Unknown:
                    return "COM error: " + ex.HResult;

                default:
                    return "Error: " + status;
            }
        }
コード例 #15
0
ファイル: Utils.cs プロジェクト: Regisfra/Regisfra.WebApp
        public static void AddException(Exception exception, string comments = null, LogExceptionLevel level = LogExceptionLevel.Low)
        {
            if (exception == null)
                return;

            try
            {
                var baseException = exception.GetBaseException();
                using (var db = new DbEntities())
                {
                    db.InsertException(new LogException()
                    {
                        Comments = comments,
                        ExceptionLevel = (short)level,
                        InsertionTime = DateTime.Now,
                        Message = exception.Message,
                        InnerException = (exception.InnerException != null) ? exception.InnerException.Message : null,
                        StackTrace = exception.StackTrace,
                        TargetSite = (exception.TargetSite != null) ? exception.TargetSite.Name : null,
                        Source = exception.Source,
                        BaseException = (baseException != null) ? baseException.Message : null
                    });
                }
            }
            catch { }
        }
コード例 #16
0
ファイル: BaseClass.cs プロジェクト: adrianbanks/Scratch
        /// <summary>
        /// Writes an exception to the console.
        /// </summary>
        /// <remarks>
        /// The full exception information will be output, including:
        /// <list type="bullet">
        /// <item><description>the type of the exception</description></item>
        /// <item><description>the exception message</description></item>
        /// <item><description>the exception stack trace</description></item>
        /// <item><description>any <see cref="Exception.Data"/> information</description></item>
        /// </list>
        /// Inner exceptions will also have the above information output in full.
        /// </remarks>
        internal static void WE(Exception e)
        {
            WL();
            WL(new string('-', 70));
            WL(e.GetType());
            WL(new string('-', 20));
            WL(e.Message);
            WL(new string('-', 20));
            WL(e.StackTrace);

            if (e.Data.Count > 0)
            {
                WL(new string('-', 20));

                foreach (DictionaryEntry entry in e.Data)
                {
                    WL("   {0}: {1}", entry.Key, entry.Value);
                }
            }

            WL(new string('-', 70));

            Exception baseException = e.GetBaseException();

            if (baseException != e)
            {
                WE(baseException);
            }

            WL();
        }
コード例 #17
0
 string GetBaseCause( Exception ex )
 {
     var inEx = ex.GetBaseException();
     string error = null;
     error = string.Format( "{1}{0}{2}", Environment.NewLine, inEx.Message, inEx.StackTrace );
     return error;
 }
コード例 #18
0
        private static void WriteToEventLog(Exception ex)
        {
            const string source = "Health.Direct.Config.Service";

            EventLogHelper.WriteError(source, ex.Message);
            EventLogHelper.WriteError(source, ex.GetBaseException().ToString());
        }
コード例 #19
0
ファイル: Logger.cs プロジェクト: greenqloud/qloudsync
 public static void LogInfo(string type, Exception e )
 {
     string message = string.Format("{0}\n{1}\n{2}\n{3}\n", e.GetType(), e.Message, e.StackTrace, e.GetBaseException());
     if(e.InnerException != null)
         message+= e.InnerException.Message;
     LogInfo(type, message);
 }
コード例 #20
0
ファイル: JsonRpcError.cs プロジェクト: db48x/KeeFox
        public static JsonObject FromException(Exception e, bool includeStackTrace)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            JsonObject error = new JsonObject();
            error.Put("name", "JSONRPCError");
            error.Put("message", e.GetBaseException().Message);

            if (includeStackTrace)
                error.Put("stackTrace", e.StackTrace);

            JsonArray errors = new JsonArray();
                
            do
            {
                errors.Put(ToLocalError(e));
                e = e.InnerException;
            }
            while (e != null);
            
            error.Put("errors", errors);
            
            return error;
        }
コード例 #21
0
        public static void WriteLog(Exception ex, string category, string message, int priority, int eventID, string status, System.Diagnostics.TraceEventType eventType, string name, string filename)
        {
            DatabaseProviderFactory factory = new DatabaseProviderFactory(new SystemConfigurationSource(false).GetSection);
            DatabaseFactory.SetDatabaseProviderFactory(factory, false);
            LogWriterFactory logWriterFactory = new LogWriterFactory();

            Logger.SetLogWriter(logWriterFactory.Create());

            LogEntry log = new LogEntry();
            log.Categories.Add(category);
            log.Message = status + " : " + ex.GetBaseException().ToString();
            log.EventId = eventID;
            log.Priority = priority;

            if (!string.IsNullOrEmpty(name.Trim()))
                log.ManagedThreadName = name;

            log.TimeStamp = System.DateTime.Now;
            log.Severity = eventType;

            if (!string.IsNullOrEmpty(filename.Trim()))
                log.Title = category + " : " + filename + " : " + message;
            else
                log.Title = category + " : " + message;

            Logger.Write(log);
            Logger.Reset();
        }
コード例 #22
0
        public static void showError(Exception ex, string Infotext, Boolean ForceEnd = false)
        {
            string Info;

            // first log the complete exception
            _logger.Log(Infotext, true);
            _logger.Log(ex.ToString(), true);
            _logger.Log(ex.Message, true);
            _logger.Log(ex.StackTrace, true);
            if (ex.InnerException != null)
                _logger.Log(ex.InnerException.ToString(), true);

            if (Infotext.Trim().Length > 0)
                Info = Infotext + Environment.NewLine + Environment.NewLine + ex.Message + Environment.NewLine;
            else
                Info = ex.Message + Environment.NewLine;

            if (ex.InnerException != null)
                Info += Environment.NewLine + ex.GetBaseException().Message;

            Info += string.Format("{0}{0}(see detailed info in logfile \"{1}\")", Environment.NewLine, _logger.logPathName);
            Info += "Create a dump file ?";

            if (MessageBox.Show(Info, "Exception occured",MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.Yes)
               Program.CreateMiniDump("RegulatedNoiseDump.dmp");
        }
コード例 #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Error"/> class
        /// from a given <see cref="Exception"/> instance and 
        /// <see cref="HttpContext"/> instance representing the HTTP 
        /// context during the exception.
        /// </summary>
        public Error(Exception e, HttpContext context)
        {
            if (e == null) throw new ArgumentNullException("e");

            Exception = e;
            var baseException = e;

            // if it's not a .Net core exception, usually more information is being added
            // so use the wrapper for the message, type, etc.
            // if it's a .Net core exception type, drill down and get the innermost exception
            if (IsBuiltInException(e))
                baseException = e.GetBaseException();

            GUID = Guid.NewGuid();
            ApplicationName = ErrorStore.ApplicationName;
            MachineName = Environment.MachineName;
            Type = baseException.GetType().FullName;
            Message = baseException.Message;
            Source = baseException.Source;
            Detail = e.ToString();
            CreationDate = DateTime.UtcNow;
            DuplicateCount = 1;
            
            var httpException = e as HttpException;
            if (httpException != null)
            {
                StatusCode = httpException.GetHttpCode();
            }

            SetContextProperties(context);

            ErrorHash = GetHash();
        }
コード例 #24
0
ファイル: ErrorServices.cs プロジェクト: DBailey635/C1-CMS
        /// <exclude />
        public static void DocumentAdministrativeError(Exception exception)
        {

            StringBuilder consoleMsg = new StringBuilder();
            consoleMsg.AppendLine(exception.GetBaseException().ToString());

            Log.LogCritical("Web Application Error, Exception", exception);

            var httpContext = HttpContext.Current;
            if (httpContext != null && httpContext.Request != null && httpContext.Request.Url != null)
            {
                consoleMsg.AppendLine();
                consoleMsg.AppendLine("URL:     " + HttpContext.Current.Request.Url);
                if (HttpContext.Current.Request.UrlReferrer != null)
                {
                    consoleMsg.AppendLine("Referer: " + httpContext.Request.UrlReferrer.AbsolutePath);
                }
            }

            string consoleId = ConsoleInfo.TryGetConsoleId();
            if (consoleId != null)
            {
                ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem { Level = LogLevel.Error, Message = consoleMsg.ToString(), Sender = typeof(ErrorServices) }, consoleId);
            }
        }
コード例 #25
0
        public static void processError(Exception ex, string Infotext, bool noAsking)
        {
            string Info;

            // first log the complete exception
            _logger.Log(Infotext, true);
            _logger.Log(ex.ToString(), true);
            _logger.Log(ex.Message, true);
            _logger.Log(ex.StackTrace, true);
            if (ex.InnerException != null)
                _logger.Log(ex.InnerException.ToString(), true);

            if (Infotext.Trim().Length > 0)
                Info = Infotext + Environment.NewLine + Environment.NewLine + ex.Message + Environment.NewLine;
            else
                Info = ex.Message + Environment.NewLine;

            if (ex.InnerException != null)
                Info += Environment.NewLine + ex.GetBaseException().Message;

            Info += string.Format("{0}{0}(see detailed info in logfile \"{1}\")", Environment.NewLine, _logger.logPathName);

            Info += string.Format("{0}{0}Suppress exception ? (App can be unstable!)", Environment.NewLine);

            Program.CreateMiniDump("RegulatedNoiseDump_handled.dmp");

            // ask user what to do
            if (noAsking || (MessageBox.Show(Info, "Exception occured",MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.No))
            {
                MessageBox.Show("Fatal error.\r\n\r\nA dump file (\"RegulatedNoiseDump_handled.dmp\" has been created in your RegulatedNoise directory.  \r\n\r\nPlease place this in a file-sharing service such as Google Drive or Dropbox, then link to the file in the Frontier forums or on the GitHub archive.  This will allow the developers to fix this problem.  \r\n\r\nThanks, and sorry about the crash...");
                Environment.Exit(-1);
            }
        }
コード例 #26
0
ファイル: Error.cs プロジェクト: Eonix/Elmo
        public Error(Exception exception, IOwinContext owinContext)
        {
            if (exception == null)
                throw new ArgumentNullException(nameof(exception));

            Exception = exception;
            var baseException = exception.GetBaseException();

            HostName = EnvironmentUtilities.GetMachineNameOrDefault();
            TypeName = baseException.GetType().FullName;
            Message = baseException.Message;
            Source = baseException.Source;
            Detail = exception.ToString();
            User = Thread.CurrentPrincipal.Identity.Name ?? string.Empty;
            Time = DateTimeOffset.Now;

            StatusCode = owinContext.Response.StatusCode;

            var webUser = owinContext.Authentication.User;
            if (!string.IsNullOrEmpty(webUser?.Identity?.Name))
            {
                User = webUser.Identity.Name;
            }

            ServerEnvironment = owinContext.Environment.ToDictionary(pair => pair.Key, pair => pair.Value?.ToString() ?? string.Empty);
            Headers = owinContext.Request.Headers.ToDictionary(pair => pair.Key, pair => pair.Value);
            Query = owinContext.Request.Query.ToDictionary(pair => pair.Key, pair => pair.Value);
            Cookies = owinContext.Request.Cookies.ToDictionary(pair => pair.Key, pair => pair.Value);
            ApplicationName = AppDomain.CurrentDomain.FriendlyName;
        }
コード例 #27
0
        protected override void OnException(ExceptionContext filterContext)
        {
            String Errormsg = String.Empty;
            Exception unhandledException = new Exception("BASE ERROR");
            if (Server.GetLastError() != null)
                unhandledException = Server.GetLastError();
            else
                unhandledException = filterContext.Exception;
            Exception httpException = unhandledException as Exception;
            Errormsg = "發生例外網頁:{0}錯誤訊息:{1}";
            if (httpException != null /*&& !httpException.GetType().IsAssignableFrom(typeof(HttpException))*/)
            {
                Errormsg = String.Format(Errormsg, Request.Path + Environment.NewLine,unhandledException.GetBaseException().ToString() + Environment.NewLine);

                Url = System.Web.HttpContext.Current.Request.Url.PathAndQuery;
                controller = Convert.ToString(ControllerContext.RouteData.Values["controller"]);
                action = Convert.ToString(ControllerContext.RouteData.Values["action"]);
                area = Convert.ToString(ControllerContext.RouteData.DataTokens["area"]);
                NLog.Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(Url + "|controller|" + controller + "|action|" + action + "|area|" + area + "|" + Errormsg);

            }
            base.OnException(filterContext);
            filterContext.ExceptionHandled = true;
        }
コード例 #28
0
        /// <summary>
        /// Logs an error to the database for later review
        /// </summary>
        /// <returns>True if error logged ok</returns>
        public static bool Log(CMS_MainEntities context, Exception ex)
        {
            try
            {
                var errorReport = new ErrorReports { ExceptionMessage = ex.Message, StackTrace = ex.StackTrace };

                MethodBase site = ex.TargetSite;
                errorReport.ModuleFunction = (site == null) ? "Unknown" : site.Name;
                errorReport.ModuleName = site == null ? "Unknown" : site.Module.Name;

                var baseException = ex.GetBaseException();
                errorReport.BaseExceptionMessage = ((baseException.Message == "")) ? "No Message Available" : baseException.Message;

                errorReport.ErrorDate = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss tt");
                errorReport.BugFixed = false;

                context.ErrorReports.Add(errorReport);
                context.SaveChanges();

                return (true);
            }
            catch
            {
                return (false);
            }
        }
コード例 #29
0
        public static void LogException(Exception ex)
        {
            var baseError = ex.GetBaseException();
            var message = string.Format("An unhandled exception occurred. Error message is {0}.", baseError.Message);

            Logger.Error(message, ex);
        }
コード例 #30
0
ファイル: ErrorLog.cs プロジェクト: stevenbey/elfar
        public ErrorLog(string application, Exception exception)
            : this()
        {
            Application = application;

            var @base = exception.GetBaseException();

            ID = Guid.NewGuid();
            Detail = @base.ToString();
            Host = TryGetMachineName();
            Time = DateTime.Now;

            Message = @base.Message;
            Source = @base.Source;
            Type = @base.GetType().ToString();

            User = Thread.CurrentPrincipal.Identity.Name;

            var httpException = exception as HttpException;

            if (httpException != null)
            {
                Code = httpException.GetHttpCode();
                Html = httpException.GetHtmlErrorMessage();
            }
        }
コード例 #31
0
        private void SetException(Exception ex)
        {
            this.Exception = ex;
            var baseException = ex;

            // if it's not a .Net core exception, usually more information is being added
            // so use the wrapper for the message, type, etc.
            // if it's a .Net core exception type, drill down and get the innermost exception
            if (IsBuiltInException(ex))
                baseException = ex.GetBaseException();

            this.Type = baseException.GetType().FullName;
            Message = baseException.Message;
            Source = baseException.Source;

            Detail = ex.ToString();

            // todo : fix migration 4.5 > core
            //var httpException = ex as HttpException;
            //if (httpException != null)
            //{
            //    StatusCode = httpException.GetHttpCode();
            //}
            this.AddFromData(ex);
        }
コード例 #32
0
        public void Complete(Exception error)
        {
            _logger.LogDebug("DrainWrites(" + _connectionId + ")");

            var context = new LifetimeContext(_transport, _lifetimeTcs, error);

            _transport.ApplyState(TransportConnectionStates.QueueDrained);

            // Drain the task queue for pending write operations so we don't end the request and then try to write
            // to a corrupted request object.
            _writeQueue.Drain().Catch(_logger).Finally(state =>
            {
                // Ensure delegate continues to use the C# Compiler static delegate caching optimization.
                ((LifetimeContext)state).Complete();
            },
            context);

            if (error != null)
            {
                _logger.LogError("CompleteRequest (" + _connectionId + ") failed: " + error.GetBaseException());
            }
            else
            {
                _logger.LogInformation("CompleteRequest (" + _connectionId + ")");
            }
        }
コード例 #33
0
 private System.Windows.Forms.TreeNode Exception2TreeNode(string name, System.Exception e)
 {
     if (name == null || name == "")
     {
         name = e.GetType().ToString();
     }
     else
     {
         name += ":\t" + e.GetType().ToString();
     }
     System.Windows.Forms.TreeNode tn = new TreeNode(name);
     tn.Nodes.Add("Message:" + e.Message);
     tn.Nodes.Add("HelpLink:\t" + e.HelpLink);
     tn.Nodes.Add("Source:\t" + e.Source);
     tn.Nodes.Add(this.StackTrace2TreeNode(e.StackTrace));
     tn.Nodes.Add("TargetSite:\t" + e.TargetSite);
     System.Exception e2 = e.InnerException;
     if (e2 != null)
     {
         tn.Nodes.Add(this.Exception2TreeNode("InnerException", e2));
     }
     e2 = e.GetBaseException();
     if (e2 != null && e != e2)
     {
         tn.Nodes.Add(this.Exception2TreeNode("BaseException", e2));
     }
     return(tn);
 }
コード例 #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Error"/> class
        /// from a given Exception instance and 
        /// HttpContext instance representing the HTTP 
        /// context during the exception.
        /// </summary>
        public Error(Exception e, string applicationName = null)
            : this(applicationName)
        {
            if (e == null) throw new ArgumentNullException(/*nameof(e)*/);

            this.Exception = e;
            var baseException = e;

            // if it's not a .Net core exception, usually more information is being added
            // so use the wrapper for the message, type, etc.
            // if it's a .Net core exception type, drill down and get the innermost exception
            if (IsBuiltInException(e))
                baseException = e.GetBaseException();

            Type = baseException.GetType().FullName;
            Message = baseException.Message;
            Source = baseException.Source;
            Detail = e.ToString();

            // todo : fix it with the right package 4.5 > core
            //var httpException = e as HttpException;
            //if (httpException != null)
            //{
            //    StatusCode = httpException.GetHttpCode();
            //}

            this.AddFromData(e);
            ErrorHash = GetHash();
        }
コード例 #35
0
        private Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            ApiError apiError = null;
            int      code     = 0;

            if (exception is ApiException)
            {
                var ex = exception as ApiException;
                if (ex.IsModelValidatonError)
                {
                    apiError = new ApiError(ResponseMessageEnum.ValidationError.GetDescription(), ex.Errors)
                    {
                        ReferenceErrorCode    = ex.ReferenceErrorCode,
                        ReferenceDocumentLink = ex.ReferenceDocumentLink,
                    };
                }
                else
                {
                    apiError = new ApiError(ex.Message)
                    {
                        ReferenceErrorCode    = ex.ReferenceErrorCode,
                        ReferenceDocumentLink = ex.ReferenceDocumentLink,
                    };
                }

                code = ex.StatusCode;
                context.Response.StatusCode = code;
            }
            else if (exception is UnauthorizedAccessException)
            {
                apiError = new ApiError(ResponseMessageEnum.UnAuthorized.GetDescription());
                code     = (int)HttpStatusCode.Unauthorized;
                context.Response.StatusCode = code;
            }
            else
            {
                var exceptionMessage = ResponseMessageEnum.Unhandled.GetDescription();
#if !DEBUG
                var    message    = exceptionMessage;
                string stackTrace = null;
#else
                var    message    = $"{ exceptionMessage } { exception.GetBaseException().Message }";
                string stackTrace = exception.StackTrace;
#endif

                apiError = new ApiError(message)
                {
                    Details = stackTrace
                };
                code = (int)HttpStatusCode.InternalServerError;
                context.Response.StatusCode = code;
            }

            var jsonString = ConvertToJSONString(GetErrorResponse(code, apiError));

            context.Response.ContentType = "application/json";
            return(context.Response.WriteAsync(jsonString));
        }
コード例 #36
0
        /// <summary>
        /// This method provide formatted exception message.
        /// </summary>
        /// <param name="message">Custom exception message.</param>
        /// <param name="e">Exception</param>
        /// <returns></returns>
        public string Format(string message, System.Exception e)
        {
            if (e.GetBaseException() != null)
            {
                e = e.GetBaseException();
            }

            // Display an error to the "poor" user
            string s = string.Format("Date: {0}", DateTime.Now);

            s += System.Environment.NewLine + string.Format("Title: {0}", string.IsNullOrEmpty(message) ? "An internal error has occurred and has been logged. Please contact your system administrator for help." : message);

            s += System.Environment.NewLine + String.Format("Exception: {0}", e.ToString());

            s += System.Environment.NewLine + String.Format("Stack Trace: {0}", e.StackTrace.ToString());

            StackTrace objStackTrace = new StackTrace(e, true);
            string     methodName    = string.Empty;
            int        lineNo        = 0;

            if (objStackTrace.FrameCount > 0)
            {
                StackFrame stackFrame = objStackTrace.GetFrame(objStackTrace.FrameCount - 1);
                methodName = stackFrame.GetMethod().Name;
                lineNo     = stackFrame.GetFileLineNumber();
            }

            if (!string.IsNullOrEmpty(methodName))
            {
                s += System.Environment.NewLine + string.Format("Method Name: {0}", methodName);
            }

            if (lineNo > 0)
            {
                s += System.Environment.NewLine + string.Format("Line No.: {0}", lineNo);
            }

            s += System.Environment.NewLine + "===============================================================================================================================";

            s += System.Environment.NewLine + System.Environment.NewLine;

            return(s);
        }
コード例 #37
0
        /// <summary>
        /// Failures the specified exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <returns></returns>
        public static VolatilityState Failure(System.Exception exception)
        {
            VolatilityState state =
                new VolatilityState(VolatilityStateType.Failure, exception.GetBaseException().Message)
            {
                FailureException = exception
            };

            return(state);
        }
コード例 #38
0
        /// <summary>
        /// 保存异常信息到文件。
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static int Save(System.Exception e)
        {
            string fileName = "Error_" + getDataTime() + ".log";
            string filePath = getSavePath();

            filePath += fileName;

            string   error = "";
            DateTime now   = DateTime.Now;
            string   CrLf  = Convert.ToString((char)13) + Convert.ToString((char)10);
            string   Tab   = Convert.ToString((char)9);

            error += getDataTime_CN();

            error += CrLf + CrLf;
            error += "Error:" + e.Message;
            error += CrLf + CrLf;
            error += "Source:" + e.Source;
            error += CrLf + CrLf;
            error += "StackTrace:" + e.StackTrace;
            error += CrLf + CrLf;

            if (e.InnerException != null)
            {
                error += "InnerException";
                error += CrLf;
                error += "______________________________________________________________________";
                error += CrLf + CrLf;
                error += "Error:" + e.InnerException.Message;
                error += CrLf + CrLf;
                error += "Source:" + e.InnerException.Source;
                error += CrLf + CrLf;
                error += "StackTrace:" + e.InnerException.StackTrace;
                error += CrLf + CrLf;
            }
            System.Exception baseExp = e.GetBaseException();
            if (baseExp != null)
            {
                error += "BaseException";
                error += CrLf;
                error += "______________________________________________________________________";
                error += CrLf + CrLf;
                error += "Error:" + baseExp.Message;
                error += CrLf + CrLf;
                error += "Source:" + baseExp.Source;
                error += CrLf + CrLf;
                error += "StackTrace:" + baseExp.StackTrace;
                error += CrLf + CrLf;
            }
            SaveTo(filePath, error);
            return(0);
        }
コード例 #39
0
        private static Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            ApiError    apiError    = null;
            APIResponse apiResponse = null;
            int         code        = 0;

            if (exception is ApiException)
            {
                var ex = exception as ApiException;
                apiError = new ApiError(ex.Message);
                apiError.ValidationErrors      = ex.Errors;
                apiError.ReferenceErrorCode    = ex.ReferenceErrorCode;
                apiError.ReferenceDocumentLink = ex.ReferenceDocumentLink;
                code = ex.StatusCode;
                context.Response.StatusCode = code;
            }
            else if (exception is UnauthorizedAccessException)
            {
                apiError = new ApiError("Unauthorized Access");
                code     = (int)HttpStatusCode.Unauthorized;
                context.Response.StatusCode = code;
            }
            else if (exception is Exception)
            {
                apiError = new ApiError(exception.Message);
                code     = (int)HttpStatusCode.InternalServerError;
                context.Response.StatusCode = code;
            }
            else
            {
#if !DEBUG
                var    msg   = "An unhandled error occurred.";
                string stack = null;
#else
                var    msg   = exception.GetBaseException().Message;
                string stack = exception.StackTrace;
#endif

                apiError                    = new ApiError(msg);
                apiError.Details            = stack;
                code                        = (int)HttpStatusCode.InternalServerError;
                context.Response.StatusCode = code;
            }

            context.Response.ContentType = "application/json";

            apiResponse = new APIResponse(code, ResponseMessageEnum.Exception.GetDescription(), null, false, apiError);

            var json = JsonConvert.SerializeObject(apiResponse);

            return(context.Response.WriteAsync(json));
        }
コード例 #40
0
ファイル: Lua_System_Exception.cs プロジェクト: zxsean/Cs2Lua
 static public int GetBaseException(IntPtr l)
 {
     try {
         System.Exception self = (System.Exception)checkSelf(l);
         var ret = self.GetBaseException();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #41
0
        private async Task HandleExceptionAsync(HttpContext httpContext, System.Exception exception)
        {
            _logger.LogError("Api Exception:", exception);

            ApiError    apiError    = null;
            ApiResponse apiResponse = null;
            int         code        = 0;

            if (exception is ApiException)
            {
                var ex = exception as ApiException;
                apiError = new ApiError(ResponseMessageEnum.ValidationError.GetDescription(), ex.Errors)
                {
                    ValidationErrors      = ex.Errors,
                    ReferenceErrorCode    = ex.ReferenceErrorCode,
                    ReferenceDocumentLink = ex.ReferenceDocumentLink
                };
                code = ex.StatusCode;
                httpContext.Response.StatusCode = code;
            }
            else if (exception is UnauthorizedAccessException)
            {
                apiError = new ApiError("Unauthorized Access");
                code     = Status401Unauthorized;
                httpContext.Response.StatusCode = code;
            }
            else
            {
#if !DEBUG
                var    msg   = "An unhandled error occurred.";
                string stack = null;
#else
                var    msg   = exception.GetBaseException().Message;
                string stack = exception.StackTrace;
#endif

                apiError = new ApiError(msg)
                {
                    Details = stack
                };
                code = Status500InternalServerError;
                httpContext.Response.StatusCode = code;
            }

            httpContext.Response.ContentType = "application/json";

            apiResponse = new ApiResponse(code, ResponseMessageEnum.Exception.GetDescription(), null, apiError);

            await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(apiResponse));
        }
コード例 #42
0
        public string ParseException(System.Exception ex)
        {
            // root cause, returns current ex if InnerException is null
            var e = ex.GetBaseException();

            // Type (@class:method) {message}
            var errorMessage = e.GetType().ToString();

            if (e.TargetSite != null)
            {
                errorMessage += " (@" + e.TargetSite.DeclaringType.FullName + ":" + e.TargetSite.Name + ")";
            }

            errorMessage += " {" + e.Message + "}";

            return(errorMessage);
        }
コード例 #43
0
 public void WriteException(System.Exception e, string message = "", bool stackTrace = false)
 {
     lock (_sb)
     {
         _sb.Clear();
         _sb.AppendLine(GetExecutionInfo() + " " + message + Environment.NewLine + "Exception was: " + e.Message);
         if (e.InnerException != null)
         {
             _sb.AppendLine("InnerException was: " + e.InnerException.Message);
         }
         _sb.AppendLine("GetBaseException().Message was: " + e.GetBaseException().Message);
         if (stackTrace)
         {
             _sb.AppendLine("StackTrace: " + e.StackTrace);
         }
         WriteErrorLine(_sb.ToString());
     }
 }
コード例 #44
0
        public static void SendErrorResponse(HttpResponseBase response, System.Exception e)
        {
            HttpException he = null;

            if (e is HttpException)
            {
                he = (HttpException)e;
            }
            else if (e is NullReferenceException)
            {
                NullReferenceException nre = (NullReferenceException)e;
                he = new HttpException(500, "NullReferenceException - The system tried to use an object with no value.", e);
            }
            else
            {
                he = new HttpException(500, e.GetBaseException().Message, e);
            }

            SendErrorResponse(response, he);
        }
コード例 #45
0
ファイル: UserAsyncResult.cs プロジェクト: formist/LinkMe
        public void SetComplete(object message, bool completedSynchronously, System.Exception exception)
        {
            if (Interlocked.Increment(ref m_setCompleteCount) == 1)               // prevent possible race conditions in the caller's code
            {
                m_completed = true;
                m_completedSynchronously = completedSynchronously;
                m_message   = message;
                m_context   = CurrentContext.DetachRequestContext();
                m_exception = (exception == null) ? null : exception.GetBaseException();

                if (m_completeEvent != null)
                {
                    ((ManualResetEvent)m_completeEvent).Set();
                }

                if (m_userCallback != null)
                {
                    m_userCallback(this);
                }
            }
        }
コード例 #46
0
        private Task HandleExceptionAsync(HttpContext filterContext, System.Exception exception)
        {
            string message;

            if (exception is MyFilterException)
            {
                var ex = exception as MyFilterException;

                message = ex.Message;

                filterContext.Response.StatusCode = 543;

                _logger.LogWarning($"Application thrown error: {message}", ex);
            }
            else if (exception is UnauthorizedAccessException)
            {
                var ex = exception as UnauthorizedAccessException;

                message = ex.Message;

                filterContext.Response.StatusCode = 444;

                _logger.LogWarning($"Application thrown error: {message}", ex);
            }
            else
            {
                message = exception.GetBaseException().Message;

                filterContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                _logger.LogError($"Unhandled exception: {message}", exception.StackTrace);
            }

            var result = JsonConvert.SerializeObject(message);

            return(filterContext.Response.WriteAsync(result));
        }
コード例 #47
0
        /// <summary>获取内部真实异常</summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public virtual Exception GetTrue(Exception ex)
        {
            if (ex == null)
            {
                return(null);
            }

            if (ex is AggregateException)
            {
                return(GetTrue((ex as AggregateException).Flatten().InnerException));
            }

            if (ex is TargetInvocationException)
            {
                return(GetTrue((ex as TargetInvocationException).InnerException));
            }

            if (ex is TypeInitializationException)
            {
                return(GetTrue((ex as TypeInitializationException).InnerException));
            }

            return(ex.GetBaseException() ?? ex);
        }
コード例 #48
0
        private string CreateErrorMessage(System.Exception ex)
        {
            var baseException = ex.GetBaseException();

            return(baseException.Message);
        }
コード例 #49
0
        /// <summary>
        /// 记录一个异常或者消息。
        /// 注意:这个方法可能会抛出异常,例如:没有写文件权限。
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="message">额外的消息</param>
        public static void LogException(System.Exception ex, string message)
        {
            if (ex == null && string.IsNullOrEmpty(message))
            {
                return;
            }

            if (ex is NotSupportedException)
            {
                return;
            }
            if (ex is NotImplementedException)
            {
                return;
            }

            if (ex is HttpException)
            {
                HttpException ee       = ex as HttpException;
                int           httpCode = ee.GetHttpCode();
                if (httpCode == 404 /* || httpCode == 403 */)
                {
                    return;
                }
            }


            LogInfo info = new LogInfo();

            info.Time = DateTime.Now;

            if (ex != null)
            {
                info.ExceptionType = ex.GetBaseException().GetType().ToString();
                info.Exception     = ex.ToString();
            }
            info.Message = message;

            HttpContext current = HttpContext.Current;

            if (current != null)
            {
                // web application

                info.Url             = current.Request.RawUrl;
                info.RequestType     = current.Request.RequestType;
                info.ContentEncoding = current.Request.ContentEncoding.ToString();

                if (current.Request.UrlReferrer != null)
                {
                    info.UrlReferrer = current.Request.UrlReferrer.ToString();
                }

                if (current.Request.Browser != null)
                {
                    info.Browser = current.Request.Browser.Type;
                }

                if (current.Request.IsAuthenticated)
                {
                    info.UserName = current.User.Identity.Name;
                }

                if (current.Request.RequestType == "POST")
                {
                    if (current.Request.Files.Count == 0)
                    {
                        current.Request.InputStream.Position = 0;
                        StreamReader reader = new StreamReader(current.Request.InputStream, current.Request.ContentEncoding);
                        info.PostData = reader.ReadToEnd();
                        reader.Close();
                        current.Request.InputStream.Position = 0;
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string name in current.Request.Form.AllKeys)
                        {
                            string[] values = current.Request.Form.GetValues(name);
                            if (values != null)
                            {
                                foreach (string value in values)
                                {
                                    sb.AppendFormat("&{0}={1}", HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
                                }
                            }
                        }

                        if (sb.Length > 0)
                        {
                            sb.Remove(0, 1);
                            info.PostData = sb.ToString();
                        }
                    }
                }

                if (current.Request.Cookies.Count > 0)
                {
                    foreach (string cookieName in current.Request.Cookies.AllKeys)
                    {
                        HttpCookie cookie = current.Request.Cookies[cookieName];
                        info.Cookie.Add(new NameValue {
                            Name = cookie.Name, Value = cookie.Value
                        });
                    }
                }

                if (current.Session != null)
                {
                    foreach (string sessionKey in current.Session.Keys)
                    {
                        object sessionValue = current.Session[sessionKey];
                        info.Session.Add(new NameValue {
                            Name  = sessionKey,
                            Value = sessionValue == null ? null : sessionValue.ToString()
                        });
                    }
                }
            }

            string filePath = string.Format("{0}\\{1}.log", s_logfileFolder, DateTime.Now.ToString("yyyy-MM-dd"));

            string xml = XmlHelper.XmlSerialize(info, Encoding.UTF8);

            FileLoger.SaveToFile(xml, filePath);
        }
コード例 #50
0
        public async Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            if (_options.UseCustomExceptionFormat)
            {
                await WriteFormattedResponseToHttpContextAsync(context, context.Response.StatusCode, exception.GetBaseException().Message);

                return;
            }

            string exceptionMessage = default;
            object apiError;
            int    httpStatusCode;

            if (exception is ApiException)
            {
                var ex = exception as ApiException;
                if (ex.IsModelValidatonError)
                {
                    apiError = new ApiError(ResponseMessage.ValidationError, ex.Errors)
                    {
                        ReferenceErrorCode = ex.ReferenceErrorCode, ReferenceDocumentLink = ex.ReferenceDocumentLink
                    };
                }
                else if (ex.IsCustomErrorObject)
                {
                    apiError = ex.CustomError;
                }
                else
                {
                    apiError = new ApiError(ex.Message)
                    {
                        ReferenceErrorCode = ex.ReferenceErrorCode, ReferenceDocumentLink = ex.ReferenceDocumentLink
                    };
                }

                httpStatusCode = ex.StatusCode;
            }
            else if (exception is UnauthorizedAccessException)
            {
                apiError       = new ApiError(ResponseMessage.UnAuthorized);
                httpStatusCode = Status401Unauthorized;
            }
            else
            {
                string stackTrace = null;

                if (_options.IsDebug)
                {
                    exceptionMessage = $"{ exceptionMessage } { exception.GetBaseException().Message }";
                    stackTrace       = exception.StackTrace;
                }
                else
                {
                    exceptionMessage = ResponseMessage.Unhandled;
                }

                apiError = new ApiError(exceptionMessage)
                {
                    Details = stackTrace
                };
                httpStatusCode = Status500InternalServerError;
            }


            if (_options.EnableExceptionLogging)
            {
                var errorMessage = apiError is ApiError ? ((ApiError)apiError).ExceptionMessage : ResponseMessage.Exception;
                _logger.Log(LogLevel.Error, exception, $"[{httpStatusCode}]: { errorMessage }");
            }

            var jsonString = ConvertToJSONString(GetErrorResponse(httpStatusCode, apiError));

            await WriteFormattedResponseToHttpContextAsync(context, httpStatusCode, jsonString);
        }
コード例 #51
0
        public Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            object apiError = null;
            int    code     = 0;

            if (exception is ApiException)
            {
                var ex = exception as ApiException;
                if (ex.IsModelValidatonError)
                {
                    apiError = new ApiError(ResponseMessageEnum.ValidationError.GetDescription(), ex.Errors)
                    {
                        ReferenceErrorCode    = ex.ReferenceErrorCode,
                        ReferenceDocumentLink = ex.ReferenceDocumentLink,
                    };

                    if (_options.EnableExceptionLogging)
                    {
                        _logger.Log(LogLevel.Warning, exception, $"[{ex.StatusCode}]: {ResponseMessage.ValidationError}");
                    }
                }
                else if (ex.IsCustomErrorObject) //new addition
                {
                    apiError = ex.CustomError;

                    if (_options.EnableExceptionLogging)
                    {
                        _logger.Log(LogLevel.Warning, exception, $"[{ex.StatusCode}]: {ResponseMessage.Exception}");
                    }
                }
                else
                {
                    apiError = new ApiError(ex.Message)
                    {
                        ReferenceErrorCode    = ex.ReferenceErrorCode,
                        ReferenceDocumentLink = ex.ReferenceDocumentLink,
                    };

                    if (_options.EnableExceptionLogging)
                    {
                        _logger.Log(LogLevel.Warning, exception, $"[{ex.StatusCode}]: {ResponseMessage.Exception}");
                    }
                }

                code = ex.StatusCode;
            }
            else if (exception is UnauthorizedAccessException)
            {
                apiError = new ApiError(ResponseMessageEnum.UnAuthorized.GetDescription());
                code     = (int)HttpStatusCode.Unauthorized;

                if (_options.EnableExceptionLogging)
                {
                    _logger.Log(LogLevel.Warning, exception, $"[{code}]: {ResponseMessage.UnAuthorized}");
                }
            }
            else
            {
                string exceptionMessage = string.Empty;
                string stackTrace       = null;

                if (_options.IsDebug)
                {
                    exceptionMessage = $"{ exceptionMessage } { exception.GetBaseException().Message }";
                    stackTrace       = exception.StackTrace;
                }
                else
                {
                    exceptionMessage = ResponseMessage.Unhandled;
                }

                apiError = new ApiError(exceptionMessage)
                {
                    Details = stackTrace
                };
                code = (int)HttpStatusCode.InternalServerError;

                if (_options.EnableExceptionLogging)
                {
                    _logger.Log(LogLevel.Error, exception, $"[{code}]: {exceptionMessage}");
                }
            }

            var jsonString = ConvertToJSONString(GetErrorResponse(code, apiError));

            return(WriteFormattedResponseToHttpContext(context, code, jsonString, true));
        }
コード例 #52
0
ファイル: EToString.cs プロジェクト: wtujvk/NETCoreDemo
 public EToString(HttpContext context, System.Exception exception)
 {
     _context   = context;
     _exception = exception.GetBaseException();
 }
コード例 #53
0
ファイル: Extensions.cs プロジェクト: zrea/Common-Extension
 public static string GetRootMessage(this Exception exception)
 {
     return(exception.GetBaseException().Message);
 }