1

I'm calling a Razor Pages handler from AJAX like this:

$.ajax({
    url: '?handler=Delete',
    data: {
        id: $(this).data('id')
    }
})
.fail(function (e) {
    alert(e.responseText);
});

And here's my handler that tests what happens if an exception occurs:

public async System.Threading.Tasks.Task OnGetDelete(int id)
{
    throw new Exception("This is an exception.");
}

If an exception is thrown in my handler, then I want to display a description of the error. The problem is that e.responseText contains way more information than I want to display to the user. It includes a description of the exception, along with the stack trace, headers and a lot of other stuff.

In the example above, I'd want to only display "This is an exception.". Is my only solution to try and parse the message from e.responseText? Is this what other people are doing?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

1 Answers1

1

In the example above, I'd want to only display "This is an exception.".

To display "This is an exception.", you can use following code snippet:

.fail(function (e) {
    //console.log(e);
    var mes = e.responseText.split('\n')[0];
    alert(mes.substring(17, mes.length - 1));
})

Test Result:

enter image description here

Update:

If possible, you can try to dynamically capture exception occurs in that specific handler method, then generate your expected response, like below.

app.Use(async (context, next) =>
{
    try
    {
        await next();
    }
    catch (Exception ex)
    {

        if (context.Request.Path.StartsWithSegments("{request_path_here}") && context.Request.Query["handler"].Any())
        {
            if (context.Request.Query["handler"]== "Delete")
            {
                context.Response.StatusCode = 500;
                var result = System.Text.Json.JsonSerializer.Serialize(new { error = ex.Message });
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(result);
            }
        }
    }
});

The responseText would be "{"error":"This is an exception."}", and you can get exception message using JSON.parse(e.responseText).error.

Test Result:

enter image description here

Fei Han
  • 26,415
  • 1
  • 30
  • 41
  • Thanks, but my specialty is parsing text. Your code is hard coding assumptions about the error text and I'm not good with that. Anyway, my question was if I have to parse it or if this information is available in a more predictable way. – Jonathan Wood Mar 18 '20 at 05:49
  • Hi @JonathanWood, please check my updates. Hoping this workaround can help achieve your requirement. – Fei Han Mar 18 '20 at 09:00
  • What is `app.Use()`? – Jonathan Wood Mar 18 '20 at 18:29
  • It could help add a middleware delegate defined in-line to the application's request pipeline. You can get more information from [here](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1). – Fei Han Mar 19 '20 at 01:41