private static ScimException IterateForScimException(Exception exception)
        {
            ScimException scimException = null;

            if (exception != null)
            {
                scimException = exception as ScimException;

                if (scimException == null)
                {
                    do
                    {
                        scimException = exception.InnerException as ScimException;
                        exception     = exception.InnerException;
                    }while (scimException == null && exception != null);
                }
            }

            return(scimException);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task Invoke(IOwinContext context)
        {
            try
            {
                await Next.Invoke(context);
            }
            catch (Exception ex)
            {
                ScimException responseException = FindScimException(ex);
                context.Response.Headers["Content-Type"] = "application/scim+json; charset=utf-8";
                ScimError scimError;
                int       statusCode;

                if (responseException != null)
                {
                    statusCode = (int)responseException.ScimError.Status;
                    scimError  = responseException.ScimError;
                }
                else
                {
                    Exception realException = GetFirstRealException(ex);
                    statusCode = (int)HttpStatusCode.InternalServerError;
                    scimError  = new ScimError(HttpStatusCode.InternalServerError,
                                               detail:
#if DEBUG
                                               realException.ToString()
#else
                                               realException.Message
#endif
                                               );
                }

                context.Response.StatusCode = statusCode;
                context.Response.Write(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(scimError, _SerializationSettings)));
            }
        }