0

I have a dotnet API function look like:

[HttpPost("searchbook")]
public IActionResult SearchBook([FromForm]bookquery query)
{
   if (webservice.haserror()) {
      return BadRequest("There have some error")
   }
   return webservice.data()        
}

In the javascript, I have write fetch just like

function handleErrors(response) {
  if (!response.ok) {
    response.text()
       .then(text => { throw new Error(text) });     
  }
  return response;
}

function fetchdata() {
    try {
        fetch(url, {
                method: "POST",
                body: postData
            })
                .then(handleErrors)
                .then(response => response.text())
                .then(result=> dosomething())
                 .catch(error => console.log(`Error from api message : ${error}`))
    }  
    catch (error) {
            console.log(`Error in fetch : ${error}`)
    }

but I have a problem which I can't get the error message : There have some error and which want put it to console.log but it show :

1. Error from api message : TypeError: Failed to execute 'text' on 'Response': body stream already read 
2. Uncaught (in promise) Error: Generate Report Report with reason : record not find

In the past, I do it by ajax function, like this and it work :

$.ajax({
    url: url,
    type: "POST",
    data: formData,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function (result, status, xhr) {
        dosomething();    
    },
    error: function (xhr, status, error) {
        console.log(`Error from api message : ${xhr.responseText}`)
    }
 })

so can I know to do it in fetch ? Thank you

Phil
  • 157,677
  • 23
  • 242
  • 245
Carrie Kaski
  • 133
  • 7
  • You just need to return the new rejected promise... `return response.text().then(text => { throw new Error(text) })` – Phil Feb 20 '23 at 00:03
  • it seem not work, from chrome it show two message: 1. Error from api message : TypeError: Failed to execute 'text' on 'Response': body stream already read 2. Uncaught (in promise) Error: Generate Report Report with reason : record not find even I add try {fetch ()... }catch (error) {console.log (`fetch error , detail : ${error}`)} – Carrie Kaski Feb 20 '23 at 03:22
  • You don't seem to have added `return` – Phil Feb 20 '23 at 03:28

0 Answers0