Is there a way to decode a Bad request (400) using JQuery as string in the error function?

Viewed 28

I have a JQuery function which requests data from an asp net API. When this API throws a bad request in the form of a string, I want to get this in the error function as a string. My API bad request looks like below;

    [HttpPost]
    [Route("Approve")]
    public ActionResult Approve([FromBody] int id)
    {
        try
        {
            //Approve code here

            return Ok("Approved");
        }
        catch (Exception)
        {
            return BadRequest("Failed to Approve version");
        }
    }

The text Failed to Approve version is what I want to get in my Ajax error function. My Ajax function looks like below;

        function approve(id) {

    alertify.confirm("Are you sure you want to approve this Version?",
        function () {
                    $.ajax({
        type: 'POST',
        url: "@TempData["api"]api/Versioning/Approve",
        headers: {
            'Authorization': 'Bearer @HttpContextAccessor.HttpContext.Session.GetString("token")'
        },
        data: { id: id},
        success: function () {
            alertify.set('notifier', 'position', 'top-center');
            alertify.success('Successfully approved a Document version');
            $('#datatable').DataTable().ajax.reload();

        },
        error: function () {

          //I want to get the string from the bad request here
            });
            $('#datatable').DataTable().ajax.reload();

        }
    })
        },
        function () {
            alertify.error('Cancelled');
        }).setHeader('Comfirm Aprrove?');
}

Is there a way I can get the bad request string in the Ajax error function?

1 Answers

I had to create a variable e in the error function and then access the method responseText and it displayed whatever was returned from the API as a string. Below is the code;

    error: function (e) {

     //The string from the bad request here
     console.log(e.responseText);
     //Do whatever with the text

     };
Related