简体   繁体   中英

Handle asmx C# Exception with fetch API

First of all sorry for my English...

I have an asmx in C# that send data in json with an fetch API Call in the client side, i was using the jQuery.Ajax call before, but i want to start using fetch API.

This is how i do the Fetch Call.
I call the function fetchcall passing the url and if is needed the JS object with the parameters to be send by POST

const jdata = await fetchcall(url, "")

Then in my function i do this

async function fetchcall(url, data) {
const PostData = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    dataType: 'json'
    //credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
    const response = await fetch(url, PostData)
    const json = await (handleErrors(response)).json();
   //This is a temporary solution to the problem
    if (json == 'Su sesion ha expirado favor de ir a pagina de login e iniciar session') {
        alert(json);
        return false;
    }

    return json

} catch (e) {
    console.log(e)
}}

And this is the handleErrors function

function handleErrors(response) {
if (!response.ok) {
    throw Error(response.statusText);
}
return response;

}

Right now i am testing the error without sending the credentials, so i get a error for the Session

And in my C# asmx i have this

[WebMethod(Description = "Load Countries", EnableSession = true)]
    [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public string fillcbocountries()
    {
        var authCookie = Session["uid"];
        if (authCookie == null)
            throw new Exception("Your session has expired please go to login page and start session");}

With that the web services is throwing me an error with the message of Your session has expired please go to login page and start session
But wen i check the response of the fetch API in the handleError function i only get a statusText:"Internal Server Error" and i want the message that the server respond.

With jQuery.Ajax i do this

error: function (xhr, textStatus, error) {
            var errorM = $.parseJSON(xhr.responseText);
            console.log(errorM.Message)
        }

And i get the

Your session has expired please go to login page and start session

Thank you for the help and regards

I discovered how to handle the error correctly if an exception is sent from C#

I removed the handleErrors function and check the response inside the fetchcall so if the response.ok is false then i check the json data that the server respond and get the json.Message .
This is the end code

async function fetchcall(url, data) {
const PostData = {
    method: 'POST',
    headers: {
        "Accept": "application/json",
        'Content-Type': 'application/json; charset=utf-8'
    },
    dataType: 'json',
    credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
    //const url = 'services/common.asmx/fillcbopais'
    const response = await fetch(url, PostData)
    const jdata = await response.json();
    if (!response.ok) {
        alert(jdata.Message);
        throw Error(jdata.Message)
    }
    return json

} catch (e) {
    console.log(e)

}}

In case someone else has this problem I hope I can help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM