/// <summary> /// Formats error message. /// </summary> /// <param name="config">A configuration.</param> /// <param name="error">A type of the error.</param> /// <param name="id">Error id or -1.</param> /// <param name="info">A stack information about the error.</param> /// <param name="message">A message.</param> /// <returns>A formatted plain text or HTML message depending on settings in <paramref name="config"/>.</returns> /// <exception cref="ArgumentNullException"><paramren name="config"/> is a <B>null</B> reference.</exception> public static string FormatErrorMessageOutput(LocalConfiguration config, PhpError error, int id, ErrorStackInfo info, string message) { if (config == null) { throw new ArgumentNullException("config"); } string error_str = PhpErrorText(error, id); // the error type (Warning, Error, ...) bool show_place = info.Line > 0 && info.Column > 0; // we are able to report error position string caller = FormatErrorCallerName(info, config); // current function name "foo()" or null // change the message or caller, based on the error type FormatErrorMessageText(error, ref message, ref caller); // error message string ErrorFormatString = config.ErrorControl.HtmlMessages ? (show_place ? CoreResources.error_message_html_debug : CoreResources.error_message_html) : (show_place ? CoreResources.error_message_plain_debug : CoreResources.error_message_plain); if (show_place) { return(string.Format(ErrorFormatString, error_str, caller, message, info.File, info.Line, info.Column)); } else { return(string.Format(ErrorFormatString, error_str, caller, message)); } }
/// <summary> /// Get the error type text, to be displayed on output. /// </summary> /// <param name="error"></param> /// <param name="id"></param> /// <returns>Error text.</returns> internal static string PhpErrorText(PhpError error, int id) { if (id > 0) { return(String.Format("{0} ({1})", error, id)); } else { switch (error) { // errors with spaces in the name case PhpError.Strict: return("Strict Standards"); // user errors reported as normal errors (without "User") case PhpError.UserNotice: return(PhpError.Notice.ToString()); case PhpError.UserError: return(PhpError.Error.ToString()); case PhpError.UserWarning: return(PhpError.Warning.ToString()); // error string as it is default: return(error.ToString());; } } }
/// <summary> /// Calls user error handler. /// </summary> /// <returns>Whether to report error by default handler (determined by handler's return value).</returns> /// <exception cref="ScriptDiedException">Error handler dies.</exception> private static bool CallUserErrorHandler(ScriptContext context, PhpError error, Func <ErrorStackInfo> info, string message) { LocalConfiguration config = context.Config; try { object result = PhpVariable.Dereference(config.ErrorControl.UserHandler.Invoke(new PhpReference[] { new PhpReference((int)error), new PhpReference(message), new PhpReference(new LazyStackInfo(info, true)), new PhpReference(new LazyStackInfo(info, false)), new PhpReference() // global variables list is not supported })); // since PHP5 an error is reported by default error handler if user handler returns false: return(result is bool && (bool)result == false); } catch (ScriptDiedException) { // user handler has cancelled the error via script termination: throw; } catch (PhpUserException) { // rethrow user exceptions: throw; } catch (Exception) { } return(false); }
/// <summary> /// Triggers the error by passing it to /// the user handler first (<see cref="PhpCoreConfiguration.UserErrorHandler"/> and then to /// the internal handler (<see cref="Throw(PhpError, string)"/>. /// </summary> public static void TriggerError(Context ctx, PhpError error, string message) { if (ctx == null) { throw new ArgumentNullException(nameof(ctx)); } if (message == null) { message = string.Empty; } // try the user handler var config = ctx.Configuration.Core; if (config.UserErrorHandler != null && (config.UserErrorTypes & error) != 0) { var trace = new PhpStackTrace(); if (!config.UserErrorHandler.Invoke(ctx, (int)error, message, trace.GetFilename(), trace.GetLine(), PhpValue.Null).IsFalse) { return; } } // fallback to internal handler Throw(error, message); }
void IErrorHandler.Throw(PhpError error, string message) { OnError?.Invoke(this, new ErrorEventArgs() { Error = error, Message = message }); }
public static bool UserError(string message, PhpError error) { if (((PhpErrorSet)error & PhpErrorSet.User) == 0) { return(false);// PhpException.InvalidArgument("error"); } return(TriggerError(message, error)); }
public static bool TriggerError(string message, PhpError error) { if (((PhpErrorSet)error & PhpErrorSet.User) == 0) { return(false);// PhpException.InvalidArgument("error"); } PhpException.Throw(error, message); return(true); }
/// <summary> /// Reports error thrown from inside eval. /// </summary> internal static void ThrowByEval(PhpError error, string sourceFile, int line, int column, string message) { // obsolete: // ErrorStackInfo info = new ErrorStackInfo(sourceFile,null,line,column,false); // // if (ScriptContext.CurrentContext.Config.ErrorControl.HtmlMessages) // message = CoreResources.GetString("error_message_html_eval",message,info.Line,info.Column); else // message = CoreResources.GetString("error_message_plain_eval",message,info.Line,info.Column); Throw(error, message); }
/// <summary> /// Initializes a new instance of the PhpException class with serialized data. This constructor is used /// when an exception is thrown in a remotely called method. Such an exceptions needs to be serialized, /// transferred back to the caller and then rethrown using this constructor. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception /// being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or /// destination.</param> protected PhpException(SerializationInfo info, StreamingContext context) : base(info, context) { this.error = (PhpError)info.GetValue("error", typeof(PhpError)); this.info = new ErrorStackInfo( (string)info.GetString("file"), (string)info.GetString("caller"), (int)info.GetInt32("line"), (int)info.GetInt32("column"), (bool)info.GetBoolean("libraryCaller")); }
public static void Throw(PhpError error, string message) { OnError?.Invoke(error, message); // throw PhpFatalErrorException // and terminate the script on fatal error if ((error & (PhpError)PhpErrorSets.Fatal) != 0) { throw new PhpFatalErrorException(message, innerException: null); } }
/// <summary> /// Searches for a file in the script library, current directory, included paths, and web application root respectively. /// </summary> /// <param name="errorSeverity">A severity of an error (if occures).</param> /// <param name="includedPath">A source path to the included script.</param> /// <param name="includerFullPath">Full source path to the including script.</param> /// <returns>Full path to the file or <B>null</B> path if not found.</returns> private FullPath SearchForIncludedFile(PhpError errorSeverity, string includedPath, FullPath includerFullPath) { FullPath result; string message; // // construct the delegate checking the script existance // var file_exists = applicationContext.BuildFileExistsDelegate(); // // try to find the script // if (file_exists != null) { string includer_directory = includerFullPath.IsEmpty ? WorkingDirectory : Path.GetDirectoryName(includerFullPath); // searches for file in the following order: // - incomplete absolute path => combines with RootOf(WorkingDirectory) // - relative path => searches in FileSystem.IncludePaths then in the includer source directory result = PhpScript.FindInclusionTargetPath( new InclusionResolutionContext( applicationContext, includer_directory, WorkingDirectory, config.FileSystem.IncludePaths ), includedPath, file_exists, out message); } else { message = "Script cannot be included with current configuration."; // there is no precompiled MSA available on non-web application result = FullPath.Empty; } // failure: if (result.IsEmpty) { PhpException.Throw(errorSeverity, CoreResources.GetString("script_inclusion_failed", includedPath, message, config.FileSystem.IncludePaths, WorkingDirectory)); } return(result); }
/// <summary> /// Generates a user-level error/warning/notice message. /// </summary> /// <remarks> /// Used to trigger a user error condition, it can be used in conjunction with the built-in error handler, /// or with a user defined function that has been set as the new error handler (set_error_handler()). /// This function is useful when you need to generate a particular response to an exception at runtime. /// </remarks> public static bool trigger_error(Context ctx, string error_msg, PhpError error_type = PhpError.E_USER_NOTICE) { if ((error_type & (PhpError)PhpErrorSets.User) == 0) { return(false); } PhpException.TriggerError(ctx, error_type, error_msg); // return(true); }
public void Throw(PhpError error, string message) { Trace.WriteLine(message, $"PHP ({error})"); if ((error & (PhpError)PhpErrorSets.Fatal) != 0) { LogEventSource.Instance.HandleFatal(message); Trace.Fail(message); } else { LogEventSource.Instance.HandleWarning(message); } }
/// <summary> /// Sets a new level of error reporting. /// </summary> /// <param name="ctx">Current runtime context.</param> /// <param name="level">The new level.</param> /// <returns>The original level.</returns> public static int error_reporting(Context ctx, PhpError level) { if ((level & (PhpError)PhpErrorSets.All) == 0 && level != 0) { //PhpException.InvalidArgument("level"); throw new ArgumentException(nameof(level)); } var errctx = GetErrorContext(ctx); var result = (int)errctx.ReportErrors; errctx.ReportErrors = level & (PhpError)PhpErrorSets.All; return(result); }
public static void Throw(PhpError error, string message) { Trace.WriteLine(message, $"PHP ({error})"); if ((error & (PhpError)PhpErrorSets.Fatal) != 0) { LogEventSource.Log.HandleFatal(message); // terminate the script throw new InvalidOperationException(message); } else { LogEventSource.Log.HandleWarning(message); } }
/// <summary> /// Modifies the error message and caller display text, depends on error type. /// In case of different PHP behavior. /// </summary> /// <param name="error">error type.</param> /// <param name="message">Error message, in default without any change.</param> /// <param name="caller">Caller text, in default will be modified to "foo(): ".</param> internal static void FormatErrorMessageText(PhpError error, ref string message, ref string caller) { switch (error) { case PhpError.Deprecated: case PhpError.UserNotice: caller = null; // the caller is not displayed in PHP return; default: if (caller != null) { caller += ": "; } return; } }
/// <summary> /// Reports error thrown by compiler. /// </summary> internal static void ThrowByWebCompiler(PhpError error, int id, string sourceFile, int line, int column, string message) { ErrorStackInfo info = new ErrorStackInfo(sourceFile, null, line, column, false); // gets the current script context and config: LocalConfiguration config = Configuration.Local; #if !SILVERLIGHT ReportError(config, HttpContext.Current.Response.Output, error, id, info, message); #else ReportError(config, new StreamWriter(ScriptContext.CurrentContext.OutputStream), error, id, info, message); #endif if (((PhpErrorSet)error & PhpErrorSet.Fatal) != 0) { throw new PhpException(error, message, info); } }
/// <summary> /// Public constructor of the class. /// </summary> /// <param name="handler">Error handler callback.</param> /// <param name="errors">Error types to be handled.</param> public ErrorHandlerRecord(IPhpCallable handler, PhpError errors) { Debug.Assert(handler != null); ErrorHandler = handler; ErrorTypes = errors; }
/// <summary> /// Calles library function is not supported. /// </summary> /// <param name="severity">A severity of the error.</param> public static void FunctionNotSupported(PhpError severity) { Throw(severity, CoreResources.GetString("function_not_supported")); }
public static void Throw(PhpError error, string formatString, params string[] args) { // TODO: get current Context from execution context // TODO: throw error according to configuration }
public static void Throw(PhpError error, string formatString, params string[] args) => Throw(error, string.Format(formatString, args));
/// <summary> /// Exception constructor. /// </summary> /// <param name="error">The type of PHP error.</param> /// <param name="message">The error message.</param> /// <param name="info">Information about an error gained from a stack.</param> private PhpException(PhpError error, string message, ErrorStackInfo info) : base(message) { this.info = info; this.error = error; }
public void Throw(PhpError error, string message) { Debug.WriteLine(message, "PHP"); Debug.Assert((error & (PhpError)PhpErrorSets.Fatal) == 0, message); }
/// <summary> /// Reports error thrown by compiler. /// </summary> internal static void ThrowByWebCompiler(PhpError error, int id, string sourceFile, int line, int column, string message) { ErrorStackInfo info = new ErrorStackInfo(sourceFile, null, line, column, false); // gets the current script context and config: LocalConfiguration config = Configuration.Local; #if !SILVERLIGHT ReportError(config, HttpContext.Current.Response.Output, error, id, info, message); #else ReportError(config, new StreamWriter(ScriptContext.CurrentContext.OutputStream), error, id, info, message); #endif if (((PhpErrorSet)error & PhpErrorSet.Fatal) != 0) throw new PhpException(error, message, info); }
public void Throw(PhpError error, string message) => Throw(error, message, Utilities.ArrayUtils.EmptyStrings);
/// <summary> /// Searches for a file in the script library, current directory, included paths, and web application root respectively. /// </summary> /// <param name="errorSeverity">A severity of an error (if occures).</param> /// <param name="includedPath">A source path to the included script.</param> /// <param name="includerFullPath">Full source path to the including script.</param> /// <returns>Full path to the file or <B>null</B> path if not found.</returns> private FullPath SearchForIncludedFile(PhpError errorSeverity, string includedPath, FullPath includerFullPath) { FullPath result; string message; // // construct the delegate checking the script existance // var file_exists = applicationContext.BuildFileExistsDelegate(); // // try to find the script // if (file_exists != null) { string includer_directory = includerFullPath.IsEmpty ? WorkingDirectory : Path.GetDirectoryName(includerFullPath); // searches for file in the following order: // - incomplete absolute path => combines with RootOf(WorkingDirectory) // - relative path => searches in FileSystem.IncludePaths then in the includer source directory result = PhpScript.FindInclusionTargetPath( new InclusionResolutionContext( applicationContext, includer_directory, WorkingDirectory, config.FileSystem.IncludePaths ), includedPath, file_exists, out message); } else { message = "Script cannot be included with current configuration."; // there is no precompiled MSA available on non-web application result = FullPath.Empty; } // failure: if (result.IsEmpty) { PhpException.Throw(errorSeverity, CoreResources.GetString("script_inclusion_failed", includedPath, message, config.FileSystem.IncludePaths, WorkingDirectory)); } return result; }
/// <summary> /// Calls user error handler. /// </summary> /// <returns>Whether to report error by default handler (determined by handler's return value).</returns> /// <exception cref="ScriptDiedException">Error handler dies.</exception> private static bool CallUserErrorHandler(ScriptContext context, PhpError error, ErrorStackInfo info, string message) { LocalConfiguration config = context.Config; try { object result = PhpVariable.Dereference(config.ErrorControl.UserHandler.Invoke(new PhpReference[] { new PhpReference((int)error), new PhpReference(message), new PhpReference(info.File), new PhpReference(info.Line), new PhpReference() // global variables list is not supported })); // since PHP5 an error is reported by default error handler if user handler returns false: return result is bool && (bool)result == false; } catch (ScriptDiedException) { // user handler has cancelled the error via script termination: throw; } catch (PhpUserException) { // rethrow user exceptions: throw; } catch (Exception) { } return false; }
public static void Throw(PhpError error, string formatString, params string[] args) { Context.DefaultErrorHandler?.Throw(error, formatString, args); }
public void Throw(PhpError error, string message) => Throw(error, message, Array.Empty <string>());
void IErrorHandler.Throw(PhpError error, string formatString, params string[] args) => ((IErrorHandler)this).Throw(error, string.Format(formatString, args));
/// <summary> /// Reports a PHP error. /// </summary> /// <param name="error">The error type</param> /// <param name="message">The error message.</param> public static void Throw(PhpError error, string message) { if (ThrowCallbackOverride != null) { ThrowCallbackOverride(error, message); return; } ErrorStackInfo info = new ErrorStackInfo(); bool info_loaded = false; // gets the current script context and config: ScriptContext context = ScriptContext.CurrentContext; LocalConfiguration config = context.Config; // determines whether the error will be reported and whether it is handleable: bool is_error_reported = ((PhpErrorSet)error & config.ErrorControl.ReportErrors) != 0 && !context.ErrorReportingDisabled; bool is_error_handleable = ((PhpErrorSet)error & PhpErrorSet.Handleable & (PhpErrorSet)config.ErrorControl.UserHandlerErrors) != 0; bool is_error_fatal = ((PhpErrorSet)error & PhpErrorSet.Fatal) != 0; bool do_report = true; // remember last error info context.LastErrorType = error; context.LastErrorMessage = message; context.LastErrorFile = null; // only if we are getting ErrorStackInfo, see PhpStackTrace.TraceErrorFrame context.LastErrorLine = 0; // only if we are getting ErrorStackInfo, see PhpStackTrace.TraceErrorFrame // calls a user defined handler if available: if (is_error_handleable && config.ErrorControl.UserHandler != null) { // loads stack info: if (!info_loaded) { info = PhpStackTrace.TraceErrorFrame(context); info_loaded = true; } do_report = CallUserErrorHandler(context, error, info, message); } // reports error to output and logs: if (do_report && is_error_reported && (config.ErrorControl.DisplayErrors || config.ErrorControl.EnableLogging)) // check if the error will be displayed to avoid stack trace loading { // loads stack info: if (!info_loaded) { info = PhpStackTrace.TraceErrorFrame(context); info_loaded = true; } ReportError(config, context.Output, error, -1, info, message); } // Throws an exception if the error is fatal and throwing is enabled. // PhpError.UserError is also fatal, but can be cancelled by user handler => handler call must precede this line. // Error displaying must also precede this line because the error should be displayed before an exception is thrown. if (is_error_fatal && context.ThrowExceptionOnError) { // loads stack info: if (!info_loaded) { info = PhpStackTrace.TraceErrorFrame(context); info_loaded = true; } throw new PhpException(error, message, info); } }
/// <summary> /// Modifies the error message and caller display text, depends on error type. /// In case of different PHP behavior. /// </summary> /// <param name="error">error type.</param> /// <param name="message">Error message, in default without any change.</param> /// <param name="caller">Caller text, in default will be modified to "foo(): ".</param> internal static void FormatErrorMessageText(PhpError error, ref string message, ref string caller) { switch (error) { case PhpError.Deprecated: case PhpError.UserNotice: caller = null; // the caller is not displayed in PHP return; default: if (caller != null) caller += ": "; return; } }
/// <summary> /// Reports an error to log file, event log and to output (as configured). /// </summary> private static void ReportError(LocalConfiguration config, TextWriter output, PhpError error, int id, ErrorStackInfo info, string message) { string formatted_message = FormatErrorMessageOutput(config, error, id, info, message); // logs error if logging is enabled: if (config.ErrorControl.EnableLogging) { #if SILVERLIGHT throw new NotSupportedException("Logging is not supported on Silverlight. Set EnableLogging to false."); #else // adds a message to log file: if (config.ErrorControl.LogFile != null) try { // <error>: <caller>(): <message> in <file> on line <line> string caller = (info.Caller != null) ? (info.Caller + "(): ") : null; string place = (info.Line > 0 && info.Column > 0) ? CoreResources.GetString("error_place", info.File, info.Line, info.Column) : null; Logger.AppendLine(config.ErrorControl.LogFile, string.Concat(error, ": ", caller, message, place)); } catch (Exception) { } // adds a message to event log: if (config.ErrorControl.SysLog) try { Logger.AddToEventLog(message); } catch (Exception) { } #endif } // displays an error message if desired: if (config.ErrorControl.DisplayErrors) { output.Write(config.ErrorControl.ErrorPrependString); output.Write(formatted_message); output.Write(config.ErrorControl.ErrorAppendString); } }
public void Throw(PhpError error, string formatString, params string[] args) { Debug.WriteLine(string.Format(formatString, args), "PHP"); Debug.Assert((error & (PhpError)PhpErrorSets.Fatal) == 0, string.Format(formatString, args)); }
public static bool UserError(string message, PhpError error) { if (((PhpErrorSet)error & PhpErrorSet.User) == 0) return false;// PhpException.InvalidArgument("error"); return TriggerError(message, error); }
/// <summary> /// Get the error type text, to be displayed on output. /// </summary> /// <param name="error"></param> /// <param name="id"></param> /// <returns>Error text.</returns> internal static string PhpErrorText(PhpError error, int id) { if (id > 0) { return String.Format("{0} ({1})", error, id); } else { switch (error) { // errors with spaces in the name case PhpError.Strict: return "Strict Standards"; // user errors reported as normal errors (without "User") case PhpError.UserNotice: return PhpError.Notice.ToString(); case PhpError.UserError: return PhpError.Error.ToString(); case PhpError.UserWarning: return PhpError.Warning.ToString(); // error string as it is default: return error.ToString(); ; } } }
public static void Throw(PhpError error, string formatString, string arg0, string arg1) => Throw(error, string.Format(formatString, arg0, arg1));
/// <summary> /// Formats error message. /// </summary> /// <param name="config">A configuration.</param> /// <param name="error">A type of the error.</param> /// <param name="id">Error id or -1.</param> /// <param name="info">A stack information about the error.</param> /// <param name="message">A message.</param> /// <returns>A formatted plain text or HTML message depending on settings in <paramref name="config"/>.</returns> /// <exception cref="ArgumentNullException"><paramren name="config"/> is a <B>null</B> reference.</exception> public static string FormatErrorMessageOutput(LocalConfiguration config, PhpError error, int id, ErrorStackInfo info, string message) { if (config == null) throw new ArgumentNullException("config"); string error_str = PhpErrorText(error, id); // the error type (Warning, Error, ...) bool show_place = info.Line > 0 && info.Column > 0; // we are able to report error position string caller = FormatErrorCallerName(info, config); // current function name "foo()" or null // change the message or caller, based on the error type FormatErrorMessageText(error, ref message, ref caller); // error message string ErrorFormatStringId = config.ErrorControl.HtmlMessages ? (show_place ? "error_message_html_debug" : "error_message_html") : (show_place ? "error_message_plain_debug" : "error_message_plain"); if (show_place) return CoreResources.GetString(ErrorFormatStringId, error_str, caller, message, info.File, info.Line, info.Column); else return CoreResources.GetString(ErrorFormatStringId, error_str, caller, message); }
/// <summary> /// Public constructor of the class. /// </summary> /// <param name="handler">Error handler callback.</param> /// <param name="errors">Error types to be handled.</param> public ErrorHandlerRecord(PhpCallback handler, PhpError errors) { ErrorHandler = handler; ErrorTypes = errors; }
public void Throw(PhpError error, string formatString, params string[] args) { // TODO: once this method gets called, pass the error to actual error handler PhpException.Throw(error, formatString, args); }
public static void Throw(PhpError error, string message) { Context.DefaultErrorHandler?.Throw(error, message); }
/// <summary> /// Alias of <see cref="trigger_error"/>. /// </summary> public static bool user_error(Context ctx, string error_msg, PhpError error_type = PhpError.E_USER_NOTICE) => trigger_error(ctx, error_msg, error_type);
public static bool TriggerError(string message, PhpError error) { if (((PhpErrorSet)error & PhpErrorSet.User) == 0) return false;// PhpException.InvalidArgument("error"); PhpException.Throw(error, message); return true; }