🚨 Error Handling

Handle errors gracefullly on the client and server

What is the usual way to handle errors in an async function?

Server Error Handling

Errors can happen on the server when the user submits bad data from the form. Let’s catch the errors and send a useful message back to the client.

app.post('/dream', async (req, res) => {
  try {
    // main code here
  } catch (error) {
    console.error(error)
    res.status(500).send(error?.response.data.error.message || 'Something went wrong');
  }
});

Frontend Error Handling

When the server fails, we can check the response status and display an error message to the user.

const response = await fetch(...);

if (response.ok) {
    // main code here
} else {
    const err = await response.text();
    alert(err);
    console.error(err);
}

Questions? Let's chat

Open Discord