Вы можете создать вспомогательный метод в базовом контроллере, который будет возвращать ошибку сервера, но с вашим пользовательским кодом состояния.Пример:
public abstract class MyBaseController : Controller
{
public EmptyResult ExecutionError(string message)
{
Response.StatusCode = 550;
Response.Write(message);
return new EmptyResult();
}
}
Вы будете вызывать этот метод в своих действиях, когда это необходимо.В вашем примере:
[HttpPost]
public ActionResult UpdateUser(UserInformation model){
// Instead of throwing exception
// throw new InvalidOperationException("Something went wrong");
// The thing you need is
return ExecutionError("Error Message");
// which should be received as an error to my
// $.ajax at client side...
}
Ошибки (включая пользовательский код '550') могут обрабатываться глобально на стороне клиента следующим образом:
$(document).ready(function () {
$.ajaxSetup({
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
/*------>*/ } else if (x.status == 550) { // <----- THIS IS MY CUSTOM ERROR CODE
alert(x.responseText);
} else if (x.status == 500) {
alert('Internel Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
});