Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?
For example, if I want to throw an exception on the server side v
Throw a new exception on server using:
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
I believe that the StatusDescription is returned to the Ajax call...
Example:
Try
Dim file As String = Request.QueryString("file")
If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")
Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()
sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)
file = IO.Path.Combine(sTmpFolder, file)
If IO.File.Exists(file) Then
IO.File.Delete(file)
End If
Catch ex As Exception
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
End Try
You have a JSON object of the exception thrown, in the xhr object. Just use
alert(xhr.responseJSON.Message);
The JSON object expose two other properties: 'ExceptionType' and 'StackTrace'
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
such as
success: function(data){
// data is object send form server
// property of data
// status type boolean
// msg type string
// result type string
if(data.status){ // true not error
$('#api_text').val(data.result);
}
else
{
$('#error_text').val(data.msg);
}
}
This is probably caused by the JSON field names not having quotation marks.
Change the JSON structure from:
{welcome:"Welcome"}
to:
{"welcome":"Welcome"}
Controller:
public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
response.Write(filterContext.Exception.Message);
response.ContentType = MediaTypeNames.Text.Plain;
filterContext.ExceptionHandled = true;
}
}
[ClientErrorHandler]
public class SomeController : Controller
{
[HttpPost]
public ActionResult SomeAction()
{
throw new Exception("Error message");
}
}
View script:
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
I believe the Ajax response handler uses the HTTP status code to check if there was an error.
So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.
I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.
I then set the Response.StatusCode
to either 500 or 200 whether I had an error or not.