Tengo un método simple de ASP.Net Web API que devuelve un BadRequest como este...
catch (Exception ex) { Log.Error($"CreateRequest:requestedBy:{requestedBy.FirstName} {requestedBy.Surname} {requestedBy.EmailAddress} Message:{ex.Message} Stack Trace:{ex.ToString()}"); return BadRequest(ex.Message); }El front-end que llama detecta el error de la manera habitual como esta...
$.ajax({ url: ResolveUrl(urlPath), data: jsonbody, type: 'POST', contentType: "application/json", success: function (data) { //do something with data }, error: function (response, textStatus, errorThrown) { toastr.error(response.responseJSON || response.statusText); }, complete: function (jxXHR, message) { //do something here } });El problema es el texto de estado en el objeto de respuesta en el error: el método solo tiene "BadRequest" y NO la cadena real que se pasó en ex.Message desde el back-end.
Esto ha funcionado antes sin ningún problema y lo ha estado haciendo durante años. El texto en ex.Message es "categoría de activo faltante", pero eso no se ve en ninguna parte en el objeto de respuesta en el método $.ajax.
Yo uso en error de esta manera
error: function (jqXHR, exception) { var status =jqXHR.status; //400 var message = jqXHR.responseText; var ex= exception; // 'abort' for example ....your code }https://dotnetfiddle.net/HwxlOF Hago esto. Por cierto, use el éxito de ajax para mostrar excepciones.
Vista:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script> $(function () { $("#theBtn").click(function () { alert("in the click..."); $.ajax({ type: "GET", url: "/api/values", //I changed this url async: false, cache: false, dataType: "json", contentType: "application/json", success: function (jsn) { alert(jsn); }, error: function (error) { alert("error"); console.log(error); } }); }); }); </script> </head> <body> <div> <input type="button" id="theBtn" value="Click to start ajax" /> </div> </body> </html>API:
public class ValuesController : ApiController { public HttpResponseMessage Get() { try { throw new Exception("Luke Perrin shows exception"); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.OK, ex.Message); } }El problema era que web.config anulaba el manejo de errores... es por eso que no vi el error original y vi el contenido html en su lugar... tenía esto que ahora está comentado.
<httpErrors errorMode="Custom" existingResponse="Replace"> <clear /> <remove statusCode="400" /> <remove statusCode="401" /> <remove statusCode="404" /> <remove statusCode="500" /> <error statusCode="400" path="500.html" responseMode="File" /> <error statusCode="401" path="500.html" responseMode="File" /> <error statusCode="404" path="404.html" responseMode="File" /> <error statusCode="500" path="500.html" responseMode="File" /> </httpErrors>