Blog>
Snippets

Custom Error Handling in Server Actions

Produce code that demonstrates custom error handling within server actions to send specific error messages and statuses.
const express = require('express');
const app = express();
class AppError extends Error {
  constructor(statusCode, message) {
    super(message);
    this.statusCode = statusCode;
    this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
    this.isOperational = true;
    Error.captureStackTrace(this, this.constructor);
  }
}

app.use((err, req, res, next) => {
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      status: err.status,
      message: err.message
    });
  }

  console.error('Error', err);
  return res.status(500).json({
    status: 'error',
    message: 'An unexpected error occurred'
  });
});

// Example of throwing a custom error
app.get('/example', (req, res, next) => {
  try {
    // Some logic that might throw an error
    throw new AppError(400, 'Custom error message');
  } catch (err) {
    next(err); // Passes the error to Express error handler
  }
});

app.listen(3000, () => console.log('Server is running on port 3000'));
Defines custom error class, sets up Express error handling middleware for custom errors, throws example custom error, and starts an Express server.