Vue Storefront is now Alokai! Learn More
Overview

Error Handling in Middleware

When building middleware integrations, you're essentially creating a translation layer between vendor-specific errors and your frontend. This guide will help you do that correctly.

What You'll Learn

This guide covers:

  • Why error normalization matters — Prevent circuit breaker false positives and wrong status codes
  • When to catch errors — Skip unnecessary try/catch blocks
  • How to normalize vendor responses — Transform SAP, Commerce Tools errors into consistent formats
  • Real-world patterns — Learn from production integrations

The Core Concept

Think of middleware as a language translator for errors:

Vendor API → Throws error in "vendor language" Your Middleware → Translates to "HTTP language" Frontend → Understands and shows user-friendly message

Without proper translation, you get:

  • ❌ 404 errors treated as server failures
  • ❌ Circuit breakers opening unnecessarily
  • ❌ Generic "Something went wrong" messages

With proper translation, you get:

  • ✅ Correct HTTP status codes (404, 409, 500)
  • ✅ Circuit breaker stays closed for business errors
  • ✅ Frontend shows "Product out of stock" instead of "Error"

Quick Decision Guide

"Do I need try/catch here?"

Ask yourself:

  1. Am I calling an integration method (like api.getCart())? → No try/catch needed
  2. Am I calling an external API (like Axios/Fetch)? → Yes, wrap in try/catch
  3. Am I mapping errors for frontend (like "wrong password")? → Yes, wrap in try/catch

"What should I throw?"

Most common scenarios:

  • Vendor returns success with error indicator (SAP's statusCode: 'noStock') → Use context.createHttpError()
  • External HTTP call fails → Configure error adapter in client setup (errors auto-normalize)
  • Missing request parameter → Use context.createHttpError() with status 400
  • Need custom message → Catch, transform, then throw context.createHttpError()

Guide Structure

Each section is designed to be read independently:

New to error handling? Start with When to Use try/catch — it answers the most common questions.

Building a new integration? Check Consequences first to understand why proper error handling matters, then review Examples for patterns you can copy.