Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
how to get the php error message in javascript with fetch

I try to get my customized php error message within the fetch promise in js. but it looks like the basic catch only gives me back the status text from the http response code.

my php is written in symfony

#[Route('/test', name:'test', methods: ['POST'])]
public function test(Request $req): Response
{
  return new JsonResponse(['error' => 'my Cusom Error'], 400);
}

javascript:

let btn = document.getElementById('myButton');
btn.addEventListener('click', function(event){
  const fd = new FormData(); // need it because want to send some files with it later
  fd.append('user', 'myUserName');

  fetch('/test', {method: 'POST', body: fd})
    .then((response) => {
      if(!response.ok){
        throw Error(response.statusText); 
        // how to catch the message returned form the server here?
        // the response object does not have this information
        // using response.error() returns a error that error is not function
        // response.error is undefined and has no information
        // a workaround is using the resposen.json().then((errorData) => {...}) inside here, but looks not fine for me.
      }
      return response.json();
    })
    .then((data) => {
      console.log('data received', data);
    })
    .catch((error) => {
      console.log(error);
    });
});
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can get the body just like usual.

throw await response.json();

will work normally.

about 4 years ago · Juan Pablo Isaza Report

0

My solution looks like this

let btn = document.querySelector('#myButton');
btn.addEventListener('click', (event) => {
  const fd = new FormData();
  fd.append('user', 'myUserName');

  fetch('/test', {method: 'POST', body: fd}
    .then(async (response) => {
      if(!response.ok)
        throw await response.json();
      return response.json();
    })
    .then((data) => {
      console.log('success', data);
    })
    .catch((error) => {
      console.error(error);
    })
});

and it works now. big thanks to GoldenretriverYT

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!