public static void AddExceptionToResponseMiddleware(this IServiceCollection services, IDictionary <Type, HttpStatusCode> mapping = null) { var mapper = new ExceptionMapping(); mapper.RegisterMapping(mapping); services.TryAddSingleton(mapper); services.TryAddSingleton <ExceptionToResponseMapper>(); }
public ErrorResponse ToErrorResponse() { var errors = ModelState?.AllErrors(); return(new ErrorResponse { ErrorMessage = Message, ErrorMessageI18n = ExceptionMapping.GetAttributeOfType <DescriptionAttribute>()?.Description, ErrorType = ExceptionMapping.ToString(), Errors = errors, }); }
static string CheckExceptionMapping(string adjectiveText) { if (ExceptionMapping.ContainsKey(adjectiveText)) { return(adjectiveText); } var exceptionBaseForms = from mapping in ExceptionMapping where mapping.Value.Contains(adjectiveText, StringComparer.OrdinalIgnoreCase) select mapping.Key; return(exceptionBaseForms.FirstOrDefault()); }
private IEnumerable <string> ComputeForms(string noun) { var exceptions = ExceptionMapping.GetValueOrDefault(noun); if (exceptions != null) { foreach (var exception in exceptions) { yield return(exception); } yield break; } var hyphenIndex = noun.LastIndexOf('-'); var root = FindRoot(hyphenIndex > -1 ? noun.Substring(hyphenIndex + 1) : noun); var hyphenatadAppendage = hyphenIndex > -1 ? noun.Substring(0, hyphenIndex + 1) : string.Empty; IEnumerable <string> results; if (!ExceptionMapping.TryGetValue(root, out results)) { foreach (var form in synthesize()) { yield return(form); } } else { foreach (var form in from result in results select hyphenatadAppendage + result) { yield return(form); } } yield return(hyphenatadAppendage + root); IEnumerable <string> synthesize() { for (var i = 0; i < sufficies.Length; i++) { if (root.EndsWith(endings[i]) || endings[i].Length == 0) { yield return(hyphenatadAppendage + root.Substring(0, root.Length - endings[i].Length) + sufficies[i]); yield break; } } } }
private static void CreateExceptionMapping(object baseType, ExceptionMapping em) { OldClass oc = em.Creator(em.PythonException, baseType); pythonToClr[oc] = em.CLRException; clrToPython[em.CLRException] = oc; nameToPython[em.PythonException] = oc; if (em.SubTypes != null) { for (int i = 0; i < em.SubTypes.Length; i++) { CreateExceptionMapping(oc, em.SubTypes[i]); } } }
public void MapGenericFaultsTest() { ResponseBase r = new ResponseBase(); ExceptionMapping em = new ExceptionMapping(); em.MapGenericFaults(r, null); Assert.IsTrue(r.ErrorList.Count == 0); em.MapGenericFaults(r, ""); Assert.IsTrue(r.ErrorList.Count == 0); em.MapGenericFaults(r, "<ns:ErrorInfo xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://isac.hp.com/schema/registrations/CustomeErrorSchema.xsd\" xmlns:ns0=\"http://www.w3.org/2003/05/soap-envelope\"><ns:HppFaultDetails><ns:SystemFault><ns:MsgCode>HPP_CUSTOMER_001</ns:MsgCode><ns:Desc>userid or password is wrongly keyed</ns:Desc></ns:SystemFault></ns:HppFaultDetails></ns:ErrorInfo>"); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); r = new ResponseBase(); em.MapGenericFaults(r, "<ns:ErrorInfo xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://isac.hp.com/schema/registrations/CustomeErrorSchema.xsd\" xmlns:ns0=\"http://www.w3.org/2003/05/soap-envelope\"><ns:HppFaultDetails><ns:SystemFault><ns:MsgCode>H</ns:MsgCode><ns:Desc>P</ns:Desc></ns:SystemFault></ns:HppFaultDetails></ns:ErrorInfo>"); Assert.IsTrue(r.ErrorList.Count == 0); r = new ResponseBase(); em.MapGenericFaults(r, "<ns:ErrorInfo xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://isac.hp.com/schema/registrations/CustomeErrorSchema.xsd\" xmlns:ns0=\"http://www.w3.org/2003/05/soap-envelope\"><ns:HppFaultDetails><ns:SystemFault><ns:MsgCode></ns:MsgCode><ns:Desc></ns:Desc></ns:SystemFault></ns:HppFaultDetails></ns:ErrorInfo>"); Assert.IsTrue(r.ErrorList.Count == 0); }
IEnumerable <string> ComputeForms(string containingRoot) { var hyphenIndex = containingRoot.IndexOf('-'); var root = FindRoot(hyphenIndex > -1 ? containingRoot.Substring(0, hyphenIndex) : containingRoot); var hyphenatedAppendage = hyphenIndex > -1 ? root.Substring(hyphenIndex) : ""; IEnumerable <string> exceptionalForms; if (!ExceptionMapping.TryGetValue(root, out exceptionalForms)) { foreach (var(suffix, ending) in suffices.Zip(endings)) { if (root.EndsWith(suffix, ordinalIgnoreCase) || string.IsNullOrEmpty(ending)) { if (root.EndsWith("y", ordinalIgnoreCase)) { root = root.Substring(0, root.Length - 1) + 'i'; } yield return(root + ending + hyphenatedAppendage); } } yield break; } }
public APIException(string message) : base(message) { ExceptionMapping = new ExceptionMapping(); }
public APIException() : base() { ExceptionMapping = new ExceptionMapping(); }
public override void OnException(ExceptionContext filterContext) { Exception exception = filterContext.Exception; if (filterContext.HttpContext.Request.IsAjaxRequest()) { var customException = ExceptionMapping.Map(exception); if (customException.ExceptionHandled) { filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; filterContext.HttpContext.Response.Write(customException.Message.Replace("\r\n", " ")); filterContext.ExceptionHandled = true; } else { filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 200; filterContext.ExceptionHandled = true; } return; } if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) { return; } string viewName = string.Empty; int httpCode = new HttpException(null, exception).GetHttpCode(); if (httpCode == 500) { viewName = "ErrorPage"; } else if (httpCode == 404) { viewName = "ErrorPage"; } else if (httpCode == 401) { viewName = "ErrorPage"; } //string controllerName = (string)filterContext.RouteData.Values["controller"]; //string actionName = (string)filterContext.RouteData.Values["action"]; filterContext.Result = new ViewResult { ViewName = viewName, MasterName = Master, TempData = filterContext.Controller.TempData, }; filterContext.Controller.TempData["ErrorResult.Exception"] = CreateErrorTrace(exception); filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = httpCode; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; }
/// <summary> /// Converts an EventStreamMessage to an event. /// </summary> /// <param name="eventStreamMessage">The event stream message to be converted.</param> /// <returns>The event</returns> protected T ConvertMessageToEvent(EventStreamMessage eventStreamMessage) { var eventStreamMessageHeaders = eventStreamMessage.Headers; string eventStreamMessageType; try { // Message type can be an event, an exception, or an error. This information is stored in the :message-type header. eventStreamMessageType = eventStreamMessageHeaders[HeaderMessageType].AsString(); } catch (KeyNotFoundException ex) { throw new EventStreamValidationException("Message type missing from event stream message.", ex); } switch (eventStreamMessageType) { case EventHeaderMessageTypeValue: string eventTypeKey; try { eventTypeKey = eventStreamMessageHeaders[HeaderEventType].AsString(); } catch (KeyNotFoundException ex) { throw new EventStreamValidationException("Event Type not defined for event.", ex); } try { return(EventMapping[eventTypeKey](eventStreamMessage)); } catch (KeyNotFoundException) { return(EventMapping[UnknownEventKey](eventStreamMessage)); } case ExceptionHeaderMessageTypeValue: string exceptionTypeKey; try { exceptionTypeKey = eventStreamMessageHeaders[HeaderExceptionType].AsString(); } catch (KeyNotFoundException ex) { throw new EventStreamValidationException("Exception Type not defined for exception.", ex); } try { throw ExceptionMapping[exceptionTypeKey](eventStreamMessage); } catch (KeyNotFoundException) { throw new UnknownEventStreamException(exceptionTypeKey); } case ErrorHeaderMessageTypeValue: int errorCode; try { errorCode = eventStreamMessageHeaders[HeaderErrorCode].AsInt32(); } catch (KeyNotFoundException ex) { throw new EventStreamValidationException("Error Code not defined for error.", ex); } // Error message is not required for errors. Errors do not have payloads. IEventStreamHeader errorMessage = null; var hasErrorMessage = eventStreamMessageHeaders.TryGetValue(HeaderErrorMessage, out errorMessage); throw new EventStreamErrorCodeException(errorCode, hasErrorMessage ? errorMessage.AsString() : string.Empty); default: // Unknown message type. Swallow the message to enable future message types without breaking existing clients. throw new UnknownEventStreamMessageTypeException(); } }
public void MapReturnCodeTest() { ResponseBase r = new ResponseBase(); int errorCount = 0; ExceptionMapping m = new ExceptionMapping(); // Check for unknown error m.MapReturnCode("dummyString", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.UnMappedError)); // m.MapReturnCode("<ns:FileldID>userId</ns:FileldID><ns:Desc>User ID contains invalid special characters.</ns:Desc>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); // m.MapReturnCode("><ns:FileldID>password</ns:FileldID><ns:Desc>Password cannot be the same as User ID.</ns:Desc>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.MustUseDiffPasswordOrUserName)); // Check for existing email m.MapReturnCode("<ns:FileldID>email</ns:FileldID>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.EmailExists)); // Check for ??? user id - not sure when this error occurs m.MapReturnCode("<fieldName>userId</fieldName><code>field.same</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.UserNameIsTheSame)); // Check for same password m.MapReturnCode("<fieldName>password</fieldName><code>field.same</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.PasswordIsTheSame)); // Check for short password m.MapReturnCode("<fieldName>password</fieldName><code>field.short</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.PasswordTooShort)); // Check for email not found m.MapReturnCode("<fieldName>email</fieldName><code>field.nomatch</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.EmailAddressNotFound)); r.ErrorList = new HashSet <Fault>(); errorCount = 0; // Check for profileId field missing m.MapReturnCode("<fieldName>profileId</fieldName><code>field.notfound</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); //Assert.IsTrue(r.ErrorList.Contains(Faults.ProfileIdNotFound)); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); // Check for reset guid not found m.MapReturnCode("<fieldName>guid</fieldName><code>field.notfound</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.ResetGuidNotFound)); // Check for bad user or password r.ErrorList = new HashSet <Fault>(); errorCount = 0; m.MapReturnCode("HPP_CUSTOMER_001", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); //Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidUserIdOrPwd)); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); m.MapReturnCode("HPP_CUSTOMER_001 HPP Authentication Service not available", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.AuthServiceNotAvailable)); // Check for bad token r.ErrorList = new HashSet <Fault>(); errorCount = 0; m.MapReturnCode("<ns:FaultCode>token.invalid</ns:FaultCode>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); // Check for product not found m.MapReturnCode("<ns:FaultDesc>Customer or Product not found</ns:FaultDesc>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.ProductNotFound)); // Check for bad current pwd r.ErrorList = new HashSet <Fault>(); errorCount = 0; m.MapReturnCode("<ruleNumber>422</ruleNumber><fieldName>currentPassword</fieldName>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); //Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCurrentPassword)); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); //Reset Everything and check second options since some Faults has two (or more possibilities r = new ResponseBase(); errorCount = 0; // Check for user id exist m.MapReturnCode("<fieldName>userId</fieldName><code>field.duplicate</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.UserIdExists)); // Check for short passwd m.MapReturnCode("<ns:FileldID>password</ns:FileldID><ns:Desc>Password must contain at least 6 characters.</ns:Desc>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.PasswordTooShort)); // Check for userId not found m.MapReturnCode("<ruleNumber>228</ruleNumber><fieldName>userId</fieldName>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); //Assert.IsTrue(r.ErrorList.Contains(Faults.UserIdNotFound)); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); // Check for token invalid r.ErrorList = new HashSet <Fault>(); errorCount = 0; m.MapReturnCode("<ruleNumber>235</ruleNumber><fieldName>changeUserID</fieldName><code>token.expired</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); r.ErrorList = new HashSet <Fault>(); errorCount = 0; m.MapReturnCode("<fieldName>userId</fieldName><code>field.nomatch</code>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); //Assert.IsTrue(r.ErrorList.Contains(Faults.UserIdNotFound)); Assert.IsTrue(r.ErrorList.Contains(Faults.InvalidCredentials)); // Check for HPP internal error r.ErrorList = new HashSet <Fault>(); errorCount = 0; m.MapReturnCode("<ns:FaultCode>BW-HTTP-100300</ns:FaultCode>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.HPPInternalError)); // Check for HPP internal error r.ErrorList = new HashSet <Fault>(); errorCount = 0; m.MapReturnCode("ns:FaultDesc>Technical Problem has occurred while serving the request</ns:FaultDesc>", r); Assert.IsTrue(r.ErrorList.Count == ++errorCount); Assert.IsTrue(r.ErrorList.Contains(Faults.HPPInternalError)); }
public ValidationException(ExceptionMapping exception, string message, ModelStateDictionary modelState) : this(exception, message) { ModelState = modelState; }
public ValidationException(ExceptionMapping exception, string message = null) : base(message) { ExceptionMapping = exception; }