I know this is a duplicate question but none of the others is helping me on this:
On the following Ajax:
$.ajax({
type: "POST",
url: "url",
data: {
//data
},
dataType: "json",
success: function (data) {
//do success logic
},
error: function (req, status, error) {
var err = req.responseText.Message;
console.log(err);
}
});
I need to display only the exception message returned from the server:
which is only: "Error al procesar el recorrido o el mismo es inexistente"
but the req.responseText is the following:
responseText: "System.Exception: Error al procesar el recorrido o el mismo es inexistente\r\n at
etc etc etc\r\n"
I already tried some approaches like:
response = jQuery.parseJSON( req.responseText ); but this fails on parsing
or:
req.responseJSON.Message
but shows undefined
I'm not being able to show only the custom exception message, any ideas?
Try to use req.responseJSON.value, not req.responseJSON.Message. It works fine in my side.
My test code
Javascript code
function ShowException() {
$.ajax({
type: "POST",
url: "/Home/ShowException",
data: {
type:1
},
dataType: "json",
success: function (data) {
alert(data.value);
},
error: function (req, status, error) {
var err = req.responseJSON.value;
console.log(err);
}
});
}
C# code
[HttpPost]
public IActionResult ShowException(int type)
{
try
{
if (type == 1)
{
return Ok(Json("success"));
}
else {
return NotFound(Json("404 not found"));
}
}
catch (Exception ex)
{
return BadRequest(Json("456"));
throw;
}
}