Reputation: 153
I need to differentiate between errors in my front end by sending back an error code from the validation.
Currently errors will just send back the string errorMessage
, from something like
return new ValidationResult("Some error message")
.
Can i somehow send back an error code, using an enum of error types for me to check in front end?
Theoretical Example:
return new ValidationResult("Some default error message", MyErrorEnum.notEnoughCats)
Upvotes: 0
Views: 1500
Reputation: 44
i use this way if ajax + json
private string RenderRazorViewToString(string viewName, object model, Dictionary<string, object> oDicParametresViewData = null, string sHtmlFieldPrefix = "")
{
ViewData.Model = model;
if (oDicParametresViewData != null) foreach (var param in oDicParametresViewData) ViewData[param.Key] = param.Value;
if (sHtmlFieldPrefix != "") ViewData.TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = sHtmlFieldPrefix };
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Response.StatusCode = 666;
return Json(new
{
Html = RenderRazorViewToString("view", model),
});
who call your validation result ? you can also return a partial view ?
Upvotes: 1
Reputation: 26
it's easy. only it is better to use constants as digits. You need:
/// <summary>
///
/// </summary>
public class NotFoundException : Exception
{
/// <summary>
/// Сообщение об ошибке
/// </summary>
/// <param name="message"></param>
public NotFoundException(string message, int? codeAction=null) : base(message)
{
CodeAction = codeAction;
}
public int? CodeAction { get; set; }
}
when intercept an error :
public class ErrorsFilterAttribute : ExceptionFilterAttribute, IAutofacExceptionFilter
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var errorMessage = new ErrorMessage(actionExecutedContext.Exception.Message, HttpStatusCode.InternalServerError);
if (actionExecutedContext.Exception is NotFoundException)
{
errorMessage.ErrorCode = (int)HttpStatusCode.NotFound;
isWarning = true;
errorMessage.CodeAction = ((NotFoundException) actionExecutedContext.Exception).CodeAction;
}
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse((HttpStatusCode)errorMessage.ErrorCode, errorMessage);
}
}
errorMessage it's my return class
/// <summary>
/// HTTP Code
/// </summary>
public int ErrorCode { get; set; }
/// <summary>
/// коде ошибки внутри сервиса
/// </summary>
public int? CodeAction { get; set; }
simple errors
{ "errorCode": 400, "codeAction": 2, "errors": {
"error": "bad values!" }}
Upvotes: 1