示例#1
0
        private async Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            var response = context.Response;

            response.ContentType = "application/json";
            response.StatusCode  = (int)HttpStatusCode.InternalServerError;

            if (exception.GetType().Name == "CustomValidationException")
            {
                var exceptionD = JsonConvert.DeserializeObject <Result>(exception.Message);
                await response.WriteAsync(JsonConvert.SerializeObject(new
                {
                    // customize as you need
                    Exception = new ExceptionModel
                    {
                        Code    = "VALIDATION_ERROR",
                        Message = exceptionD.Message,
                        Type    = exception.GetType().FullName,
                        Errors  = exceptionD.Errors.Select(x => new { x.PropertyName, x.ErrorMessage })
                    }
                }));
            }
            else
            {
                await response.WriteAsync(JsonConvert.SerializeObject(new
                {
                    Exception = new ExceptionModel
                    {
                        Code    = "INTERNAL_ERROR",
                        Message = exception.Message,
                        Type    = exception.GetType().FullName
                    }
                }));
            }
        }
        /// <summary>
        /// Generating Exception Information to sb
        /// </summary>
        /// <param name="e">Exception that we want to generate information on</param>
        /// <param name="sb">System.Text.StringBuilder to generate information to</param>
        public static void GenerateExceptionReport(System.Exception e, System.Text.StringBuilder sb)
        {
            if (e != null)
            {
                if (e.GetType().FullName != null)
                {
                    sb.Append("Exception type: " + e.GetType().FullName + "\r\n");
                    // This is if we know we can collect special info for a specific Exception
                    // Walk around for Windows Mobile.
#if !COMPACT_FRAMEWORK
                    switch (e.GetType().ToString())
                    {
                    case "System.Reflection.ReflectionTypeLoadException":
                        System.Reflection.ReflectionTypeLoadException rtle = (System.Reflection.ReflectionTypeLoadException)e;
                        for (int i = 0; i < rtle.LoaderExceptions.Length; i++)
                        {
                            sb.Append("\t" + rtle.LoaderExceptions[i].Message + "\r\n");
                        }
                        break;
                    }
#endif
                }
                if (e.Message != null)
                {
                    sb.Append("Exception text: " + e.Message + "\r\n");
                }
                // Walk around for Windows Mobile.
#if !COMPACT_FRAMEWORK
                if (e.TargetSite != null)
                {
                    sb.Append("Function Name: " + e.TargetSite.ToString() + "\r\n");
                }
#endif
                if (e.StackTrace != null)
                {
                    sb.Append("StackTrace: " + e.StackTrace.ToString() + "\r\n");
                }
                // Walk around for Windows Mobile.
#if !COMPACT_FRAMEWORK
                if (e.Source != null)
                {
                    sb.Append("Source: " + e.Source + "\r\n");
                }
#endif
                if (e.InnerException != null)
                {
                    sb.Append("InnerException: \r\n");
                    GenerateExceptionReport(e.InnerException, sb);
                    sb.Append("\r\n");
                }
            }
        }
示例#3
0
        public HandleExceptionResult HandleException(System.Exception originalException, HandleExceptionResult result)
        {
            //TODO: JSA, APLICAR CADENA DE RESPONSABILIDAD
            System.Exception _innerException = originalException;


            if (_innerException.GetType() == typeof(GenericException))
            {
                var genericException = _innerException as GenericException;
                result.TypeResult = TypeResult.Information;
                result.Message    = genericException.FriendlyMessage;
            }
            else
            {
                if (_innerException.GetType() == typeof(ConcurrenciaExcepcion))
                {
                    result.TypeResult = TypeResult.Error;
                    result.Message    = Mensajes.ErrorConcurrencia;
                }
                else
                {
                    if (_innerException.GetType() == typeof(NegocioExcepcion))
                    {
                        var negocioException = _innerException as NegocioExcepcion;
                        result.TypeResult = TypeResult.Error;
                        result.Message    = negocioException.FriendlyMessage;
                    }
                    else
                    {
                        if (_innerException.GetType() == typeof(DbEntityValidationException))
                        {
                            var dbEntityValidationException = _innerException as DbEntityValidationException;
                            result.TypeResult = TypeResult.Error;
                            var errorMessages = dbEntityValidationException.EntityValidationErrors
                                                .SelectMany(x => x.ValidationErrors)
                                                .Select(x => x.ErrorMessage);
                            var fullErrorMessage = string.Join("; ", errorMessages);
                            result.Message = fullErrorMessage;
                        }
                        else
                        {
                            //Default
                            result.TypeResult = TypeResult.Error;
                            result.Message    = Mensajes.ErrorGenerico;
                        }
                    }
                }
            }

            return(result);
        }
示例#4
0
        } // End Function GetExceptionStack

        public virtual string StringifyException(System.Exception ex)
        {
            System.Guid entryUID = System.Guid.NewGuid();

            string type         = ex.GetType().Name;
            string typeFullName = ex.GetType().FullName;
            string message      = ex.Message;
            string stackTrace   = ex.StackTrace;
            string source       = ex.Source;

            System.Collections.IDictionary data = ex.Data;

            return(ex.Message);
        } // End Function StringifyException
示例#5
0
        /// <summary>
        /// Returns a string representation of this exception, including
        /// any inner exceptions.
        /// </summary>
        /// <returns>The string representation of this exception.</returns>
        public override string ToString()
        {
            //
            // This prints the exception Java style. That is, the outermost
            // exception, "Caused by:" to the innermost exception. The
            // stack trace is not nicely indented as with Java, but
            // without string parsing (perhaps tokenize on "\n"), it
            // doesn't appear to be possible to reformat it.
            //
            System.IO.StringWriter     sw = new System.IO.StringWriter(CultureInfo.CurrentCulture);
            IceUtilInternal.OutputBase op = new IceUtilInternal.OutputBase(sw);
            op.setUseTab(false);
            op.print(GetType().FullName);
            op.inc();
            IceInternal.ValueWriter.write(this, op);
            sw.Write("\n");
            sw.Write(StackTrace);

            System.Exception curr = InnerException;
            while (curr != null)
            {
                sw.Write("\nCaused by: ");
                sw.Write(curr.GetType().FullName);
                if (!(curr is Ice.Exception))
                {
                    sw.Write(": ");
                    sw.Write(curr.Message);
                }
                sw.Write("\n");
                sw.Write(curr.StackTrace);
                curr = curr.InnerException;
            }

            return(sw.ToString());
        }
 /// <summary>
 /// Handling the finally from ExecuteInternal.
 /// </summary>
 /// <param name="deferred"></param>
 /// <param name="listeners"></param>
 /// <param name="context"></param>
 private void HandleFinally(ICollection <System.Exception> deferred, IRepeatListener[] listeners, IRepeatContext context)
 {
     try
     {
         if (deferred.Any())
         {
             System.Exception exception = deferred.First();
             Logger.Debug("Handling fatal exception explicitly (rethrowing first of {0}): {1} : {2}",
                          deferred.Count,
                          exception.GetType().Name,
                          exception.Message
                          );
             Rethrow(exception);
         }
     }
     finally
     {
         try
         {
             foreach (IRepeatListener interceptor in _listeners)
             {
                 interceptor.Close(context);
             }
         }
         finally
         {
             context.Close();
         }
     }
 }
        /// <summary>
        /// Handling exceptions.
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="context"></param>
        /// <param name="deferred"></param>
        private void DoHandle(System.Exception exception, IRepeatContext context, ICollection <System.Exception> deferred)
        {
            // An exception alone is not sufficient grounds for not continuing
            System.Exception unwrappedException = UnwrapIfRethrown(exception);
            try
            {
                for (int i = _listeners.Length; i-- > 0;)
                {
                    IRepeatListener interceptor = _listeners[i];
                    // This is not an error - only log at debug level.
                    Logger.Debug(unwrappedException, "Exception intercepted ({0} of {1})", (i + 1), _listeners.Length);
                    interceptor.OnError(context, unwrappedException);
                }

                Logger.Debug("Handling exception: {0}, caused by: {1} : {2}",
                             exception.GetType().Name,
                             unwrappedException.GetType().Name,
                             unwrappedException.Message
                             );

                _exceptionHandler.HandleException(context, unwrappedException);
            }
            catch (System.Exception handled)
            {
                deferred.Add(handled);
            }
        }
示例#8
0
        public static string HandlePotentialQuandlError(System.Exception e, bool reThrow = true, Dictionary <string, string> additionalData = null)
        {
            // If it's detected as a quandl error handle it but don't send out sentry message.
            if (e.GetType() == typeof(QuandlErrorBase))
            {
                return(HandleQuandlError((QuandlErrorBase)e, reThrow, additionalData));
            }

            var innerException = e.InnerException;

            if (innerException != null && innerException.GetType() == typeof(QuandlErrorBase))
            {
                QuandlErrorBase exBase = (QuandlErrorBase)e.InnerException.GetBaseException();
                CheckNoApiKey(exBase.ErrorCode);
                return(HandleQuandlError((QuandlErrorBase)innerException, reThrow, additionalData));
            }

            // We couldn't figure out how to handle it. Log and explode.
            Logger.log(e, additionalData);

            if (reThrow)
            {
                throw e;
            }
            return(null);
        }
示例#9
0
 public Exception(System.Exception exception)
 {
     _originalException = exception;
     this.AddToPayload("errorClass", TypeNameHelper.GetTypeDisplayName(exception.GetType()));
     this.AddToPayload("message", exception.Message);
     this.AddToPayload("stacktrace", new StackTrace(exception).ToArray());
 }
示例#10
0
        public static void Exception(string message, System.Exception e)
        {
#if DEBUG
            throw e;
#else
            if (FormatValid(message))
            {
                var parts      = message.Split('|');
                var prefix     = parts[1];
                var unprefixed = parts[2];
                var logger     = LogManager.GetLogger(prefix);

                System.Diagnostics.Debug.WriteLine($"ERROR|{message}");

                logger.Error("-------------------------- Begin exception --------------------------");
                logger.Error(unprefixed);

                do
                {
                    logger.Error($"Exception fulle name:\n <{e.GetType().FullName}>");
                    logger.Error($"Exception message:\n <{e.Message}>");
                    logger.Error($"Exception stack trace:\n <{e.StackTrace}>");
                    logger.Error($"Exception source:\n <{e.Source}>");
                    logger.Error($"Exception target site:\n <{e.TargetSite}>");
                    e = e.InnerException;
                } while (e != null);

                logger.Error("-------------------------- End exception --------------------------");
            }
            else
            {
                LogFaultyFormat(message);
            }
#endif
        }
示例#11
0
        private static string GetExceptionBlock(System.Exception exception)
        {
            var exceptionString = new StringBuilder();

            exceptionString.AppendLine("Excepcion Externa.");
            exceptionString.AppendLine("Tipo: " + exception.GetType().Name);
            exceptionString.AppendLine("Ayuda: " + exception.HelpLink);
            exceptionString.AppendLine("Mensaje: " + exception.Message);
            exceptionString.AppendLine("Objeto Origen: " + exception.Source);
            exceptionString.AppendLine("Metodo Origen: " + exception.TargetSite);
            exceptionString.AppendLine("StackTrace: " + exception.StackTrace);

            var internalException = exception;

            while (internalException.InnerException != null)
            {
                internalException = internalException.InnerException;
                exceptionString.AppendLine();
                exceptionString.AppendLine("Excepcion Interna.");
                exceptionString.AppendLine("Tipo: " + internalException.GetType().Name);
                exceptionString.AppendLine("Ayuda: " + internalException.HelpLink);
                exceptionString.AppendLine("Mensaje: " + internalException.Message);
                exceptionString.AppendLine("Origen: " + internalException.Source);
                exceptionString.AppendLine("Metodo: " + internalException.TargetSite);
                exceptionString.AppendLine("StackTrace: " + internalException.StackTrace);
            }

            return(exceptionString.ToString());
        }
示例#12
0
        private static Task HandleException(ref HttpContext context, ref System.Exception exception)
        {
            Devon4NetLogger.Error(exception);

            var exceptionTypeValue  = exception.GetType();
            var exceptionInterfaces = exceptionTypeValue.GetInterfaces().Select(i => i.Name).ToList();

            exceptionInterfaces.Add(exceptionTypeValue.Name);

            return(exceptionInterfaces switch
            {
                { } exceptionType when exceptionType.Contains("InvalidDataException") => HandleContext(ref context,
                                                                                                       StatusCodes.Status422UnprocessableEntity),
                {
                }

                exceptionType when exceptionType.Contains("ArgumentException") ||
                exceptionType.Contains("ArgumentNullException") ||
                exceptionType.Contains("NotFoundException") ||
                exceptionType.Contains("FileNotFoundException") => HandleContext(ref context,
                                                                                 StatusCodes.Status400BadRequest),
                {
                }

                exceptionType when exceptionType.Contains("IWebApiException") => HandleContext(ref context,
                                                                                               ((IWebApiException)exception).StatusCode, exception.Message,
                                                                                               ((IWebApiException)exception).ShowMessage),
                _ => HandleContext(ref context, StatusCodes.Status500InternalServerError, exception.Message)
            });
示例#13
0
 protected override void Verify(System.Exception exception)
 {
     if (exception.GetType() != this.exceptionType || (this.exceptionMessage != null && exception.Message != this.exceptionMessage))
     {
         Assert.Fail("Exception match failed.");
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="RollbarExceptionDto"/> class.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public RollbarExceptionDto(System.Exception exception)
        {
            Assumption.AssertNotNull(exception, nameof(exception));

            Class   = exception.GetType().FullName;
            Message = exception.Message;
        }
        private void HandleException(TextWriter writer, LoggingEvent loggingEvent)
        {
            System.Exception exceptionObject = loggingEvent.ExceptionObject;

            if (exceptionObject != null)
            {
                AddStructuredData(writer, "ExceptionSource", exceptionObject.Source);
                AddStructuredData(writer, "ExceptionType", exceptionObject.GetType().FullName);
                AddStructuredData(writer, "ExceptionMessage", exceptionObject.Message);
                AddStructuredData(writer, "EventHelp", exceptionObject.HelpLink);

                if (loggingEvent.Properties.Contains("log4net:syslog-exception-log"))
                {
                    AddStructuredData(writer, "EventLog", loggingEvent.Properties["log4net:syslog-exception-log"].ToString());
                }
            }
            else
            {
                string exceptionString = loggingEvent.GetExceptionString();
                if (!string.IsNullOrEmpty(exceptionString))
                {
                    AddStructuredData(writer, "ExceptionMessage", exceptionString);
                }
            }
        }
示例#16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Exception"/> class.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public Exception(System.Exception exception)
        {
            Assumption.AssertNotNull(exception, nameof(exception));

            this.Class   = exception.GetType().FullName;
            this.Message = exception.Message;
        }
示例#17
0
 /// <summary>
 /// 处理在服务之外抛出的异常
 /// </summary>
 /// <param name="httpRequest"></param>
 /// <param name="httpResponse"></param>
 /// <param name="operationName"></param>
 /// <param name="exception"></param>
 public void OnHandleUncaughtException(
     IHttpRequest httpRequest, IHttpResponse httpResponse, string operationName, System.Exception exception)
 {
     httpResponse.Write("Error: {0}: {1}".Fmt(exception.GetType().Name, exception.Message));
     httpResponse.EndRequest(skipHeaders: true);
     DtoUtils.HandleException(_appHost, httpResponse, exception);
 }
示例#18
0
        static string StackTrace(System.Exception e)
        {
            string answer = e.StackTrace;
            // Using seen for cycle detection to break cycling.
            List <System.Exception> seen = new List <System.Exception> ();

            seen.Add(e);
            if (answer != null)
            {
                // There has to be some way of telling where InnerException ie stacktrace
                // ends and main Exception e stacktrace begins.  This is it.
                answer = ((e.GetType().FullName + " : " + e.Message + "\r\n")
                          + answer);
                System.Exception ie = e.InnerException;
                while ((ie != null) && (seen.IndexOf(ie) < 0))
                {
                    seen.Add(ie);
                    answer = ((ie.GetType().FullName + " : " + ie.Message + "\r\n")
                              + (ie.StackTrace + "\r\n")
                              + answer);
                    ie = ie.InnerException;
                }
            }
            else
            {
                answer = "";
            }
            return(answer);
        }
示例#19
0
        /// <summary>
        ///     以自定义用户信息和异常对象实例化一个异常信息对象
        /// </summary>
        /// <param name="e"> 异常对象 </param>
        /// <param name="userMessage"> 自定义用户信息 </param>
        /// <param name="isHideStackTrace"> 是否隐藏异常堆栈信息 </param>
        public ExceptionMessage(System.Exception e, string userMessage = null, bool isHideStackTrace = false)
        {
            UserMessage = string.IsNullOrEmpty(userMessage) ? e.Message : userMessage;

            StringBuilder sb = new StringBuilder();

            ExMessage = string.Empty;
            int    count     = 0;
            string appString = "";

            while (e != null)
            {
                if (count > 0)
                {
                    appString += " ";
                }
                ExMessage = e.Message;
                sb.AppendLine(appString + "异常消息:" + e.Message);
                sb.AppendLine(appString + "异常类型:" + e.GetType().FullName);
                sb.AppendLine(appString + "异常方法:" + (e.TargetSite == null ? null : e.TargetSite.Name));
                sb.AppendLine(appString + "异常源:" + e.Source);
                if (!isHideStackTrace && e.StackTrace != null)
                {
                    sb.AppendLine(appString + "异常堆栈:" + e.StackTrace);
                }
                if (e.InnerException != null)
                {
                    sb.AppendLine(appString + "内部异常:");
                    count++;
                }
                e = e.InnerException;
            }
            ErrorDetails = sb.ToString();
            sb.Clear();
        }
示例#20
0
        private string _ToFieldTypeConvertorError(System.Exception e)
        {
            var trace = new System.Diagnostics.StackTrace(e, true);
            var frame = trace.GetFrame(0);
            var cause = "";

            for (var n = 1; n < trace.FrameCount; ++n)
            {
                var tmp = trace.GetFrame(n);
                var mb  = tmp.GetMethod();
                var mfn = mb.DeclaringType + "." + mb.Name;
                if (mfn == "InfSprout.XlsxParser.DataTable._ParseCellValues")
                {
                    frame = trace.GetFrame(n - 1);
                    if (n > 1)
                    {
                        cause = string.Format(", {0}()",
                                              trace.GetFrame(n - 2).GetMethod().Name
                                              );
                    }
                    break;
                }
            }
            var error = string.Format("{0}(\"{1}\") at {2}:{3}{4}",
                                      e.GetType(), e.Message, frame.GetMethod().DeclaringType,
                                      frame.GetFileLineNumber(), cause
                                      );

            return(error.ToSingleLine());
        }
        void LogException(CompileTaskResult result, System.Exception e, SyntaxNode node, out string logMessage)
        {
            logMessage = "";

            if (node != null)
            {
                FileLinePositionSpan lineSpan = node.GetLocation().GetLineSpan();

                CompileError error = new CompileError();
                error.script   = programAsset.sourceCsScript;
                error.errorStr = $"{e.GetType()}: {e.Message}";
                error.lineIdx  = lineSpan.StartLinePosition.Line;
                error.charIdx  = lineSpan.StartLinePosition.Character;

                result.compileErrors.Add(error);
            }
            else
            {
                logMessage = e.ToString();
                Debug.LogException(e);
            }
#if UDONSHARP_DEBUG
            Debug.LogException(e);
            Debug.LogError(e.StackTrace);
#endif
        }
示例#22
0
 public static bool IsExpected(System.Exception e, string expectedExceptionName)
 {
     if (e is System.Reflection.TargetInvocationException)
     {
         return(IsExpected(e as System.Reflection.TargetInvocationException, expectedExceptionName));
     }
     return(Reflection.IsA(e.GetType(), expectedExceptionName));
 }
示例#23
0
 public InnerException(System.Exception exception)
 {
     this.Code = exception.GetType().Name;
     if (exception.InnerException != null)
     {
         this.InnerError = new InnerException(exception.InnerException);
     }
 }
示例#24
0
 protected void helpBox(string n, System.Exception e)
 {
     EditorGUILayout.HelpBox
         (target.GetType() + "." + n
         + "\n" + e.GetType()
         + "\n" + e.Message
         , MessageType.Warning);
 }
示例#25
0
 public static bool IsSuccessException(System.Exception e)
 {
     if (e is System.Reflection.TargetInvocationException)
     {
         return(IsSuccessException(e as System.Reflection.TargetInvocationException));
     }
     return(Reflection.IsA(e.GetType(), typeof(NUnit.Framework.SuccessException).FullName));
 }
示例#26
0
        public ExceptionResponse(System.Exception exception)
        {
            if (exception == null)
            {
                throw new System.ArgumentNullException(nameof(exception));
            }

            ResponseStatusCode = 500;
            ResponseHeaders.Add("Exception-Type", exception.GetType().ToString());
            ResponseHeaders.Add("Exception-Message", exception.Message);
            ResponseHeaders.Add("Content-Type", "application/json; charset=utf-8");
            ResponseBody = new JsonBody(new
            {
                Message    = exception.Message,
                Type       = exception.GetType(),
                StackTrace = exception.StackTrace
            });
        }
 public static JObject GetError(System.Exception ex)
 {
     return(new JObject
     {
         { "hresult", ex.HResult.ToString("X8") },
         { "message", ex.Message },
         { "key", ex.GetType().Name },
     });
 }
示例#28
0
文件: cAbc.cs 项目: shkumat/MyTypes
 public static void Add(System.Exception Excpt, string Description)
 {
     Clear();
     ErrCode        = Excpt.GetType().ToString().Trim();
     ErrSource      = Excpt.Source.Trim();
     ErrCallStack   = Excpt.StackTrace.Trim();
     ErrDescription = Excpt.Message.Trim() + "     " + Description;
     Print(ToString());
 }
示例#29
0
        public static string ToTypeString(this System.Exception ex)
        {
            var type = ex.GetType().ToString();

            if (type.Contains("`1["))
            {
                type = type.Replace("`1[", "<").Replace("]", ">");
            }
            return(type);
        }
示例#30
0
        public static void TrackAppException(string activity, String method, Exception exception, Boolean isFatalException)
        {
            var builder = new HitBuilders.ExceptionBuilder();
            var exceptionMessageToTrack = string.Format("{0}, Method : {1}\nException type : {2}, Exception Message : {3}\nStack Trace : \n{4}", activity, method,
                                                        exception.GetType(), exception.Message, exception.StackTrace);

            builder.SetDescription(exceptionMessageToTrack);
            builder.SetFatal(isFatalException);

            Rep.Instance.GaTracker.Send(builder.Build());
        }
示例#31
0
 public void HandleExpected(Exception ex)
 {
     EasyTracker.Tracker.SendException(ex.Message, Throwable.FromException(ex), false);
     FlurryAgent.OnError(ex.GetType().Name, ex.Message, Throwable.FromException(ex));
     Crittercism.LogHandledException(Throwable.FromException(ex));
     Log.Error(_context.GetType().Name, ex.Message);
     string errorMessage = _context.Resources.GetString(Resource.String.CommonErrorMessage);
     AlertDialog dialog = new AlertDialog.Builder(_context).SetMessage(errorMessage).Create();
     dialog.SetCanceledOnTouchOutside(true);
     dialog.Show();
 }
示例#32
0
        public static void TrackAppException(string activity, String method, Exception exception, Boolean isFatalException)
        {
            var builder = new HitBuilders.ExceptionBuilder();
            var exceptionMessageToTrack = string.Format("{0}, Method : {1}\nException type : {2}, Exception Message : {3}\nStack Trace : \n{4}", activity, method,
                exception.GetType(),exception.Message, exception.StackTrace);

            builder.SetDescription(exceptionMessageToTrack);
            builder.SetFatal(isFatalException);

            Rep.Instance.GaTracker.Send(builder.Build());
        }