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

388
Views
Handling server side errors in javascript fetch

I'm making a script which has server side validation. When validation fails I have the script throw an exception server side. I want to access the message in the exception when the response reaches the client side, but I'm having trouble with that. If I console.log the data I can see the exception, but I want to access it in the catch so I can push the error message to an HTML element on the page.

    fetch(/* Posting to some PHP script */).then(function(data) {
        
        // Logic here when success  
        console.log(data) // Shows error msg when there is an error 

        
    }).catch(function() {
        // Error Handling, I want to push the error msg to HTML element here             
    });

What am I doing wrong here? Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Throw the error. It will be caught in the .catch() and you can manipulate it there

fetch(/* Posting to some PHP script */)
    .then(function(data) {
        // Logic here when success 
        console.log(data) // Shows error msg when there is an error
        if(data.error){ // Or whatever condition you need to detect there's an error
            throw data.error; // This will be caught in the catch() below
        }
    })
    .catch(function(err) {
        // You have your error here with the message from the server, display it in the HTML          
    });
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!