using System;
using xExceptions.Constants;
using xExceptions.Models;
namespace xCommons.Extensions {
///
/// this is an extension pack for Exceptions
///
public static partial class ExceptionExtensions {
///
/// determines an string contains an XError content or not
///
///
///
public static bool IsXError (this string source) {
//
if (source.IsNullOrEmpty ()) {
return false;
}
//
var xError = source.ToXError ();
if (xError != null) {
return true;
}
//
// If Convert Proccess fails ...
var normalString = source.ToNormalString ();
//
// Return result based on string values ...
return normalString.Contains ("id") && normalString.Contains ("message");
}
///
/// deserialize an string to to XError class instance
///
///
///
public static XError ToXError (this string source) {
//
if (source.IsNullOrEmpty ()) {
return null;
}
//
try {
//
var err = source.FromJSON ();
//
// if err is null we have to manually get value
if (err == null) {
//
var normalString = source.ToNormalString ();
var parts = normalString.Split (',');
if (parts.Length > 2) {
return null;
}
//
var idContainer = parts[0];
var messageContainer = parts[1];
}
//
return err;
} catch {
return null;
}
}
public static XError ToXError (this XException source) {
//
var errorId = (int) source;
var errorMessage = source.GetStringValue ();
//
return new XError {
Id = errorId,
Message = errorMessage
};
}
///
/// Convert an XError instance to an Exception
///
///
///
public static Exception ToException (this XError source) {
//
var jsonStr = source.ToJSON ();
return new Exception (jsonStr);
}
public static Exception ToException (this XException source) {
return source
.ToXError ()
.ToException ();
}
///
/// Convert an Exception to corresponding XError Object
///
///
///
public static XError FromException (this Exception source) {
//
if (source == null || source.Message.IsNullOrEmpty ()) {
return null;
}
//
return source.Message.ToXError ();
}
///
/// Add Content to Contentable XException member and return XError Object
///
///
///
///
public static XError AddContentToError (this XException exception, string value) {
//
var xError = exception.ToXError ();
xError.Message = string.Format (xError.Message, value);
//
return xError;
}
///
/// Add Content to Contentable XException member and return Exception Object
///
///
///
///
public static Exception AddContentToException (this XException exception, string value) {
//
var xError = exception.ToXError ();
xError.Message = string.Format (xError.Message, value);
//
return xError.ToException ();
}
///
/// Throw Specific Exception ...
///
///
///
public static void Throw (
this XException source,
string content = null
) {
//
Exception exception = null;
if (content.IsNullOrEmpty ()) {
exception = source.ToException ();
} else {
exception = source.AddContentToException (content);
}
//
throw exception;
}
}
}