This solution has been AI generated
You shouldn't rely on tool-thrown errors to carry auth intent. In v2 there's no UI-side onError hook yet and RUN_ERROR isn't meant for application-level auth. Instead, return an HTTP 401 from your backend and intercept it on the client transport to trigger logout.
Recommended pattern
- Use RUN_ERROR only for in-stream agent/tool failures.
- For auth failures, return HTTP 401 from your Express/Mastra layer.
- On the UI, intercept the transport error (AG-UI middleware supports RxJS
catchError) and dispatch a logout.
Backend (Express/Mastra): propagate a real 401
app.post("/agent/run", async (req, res, next) => {
try {
const r = await fetch(PROTECTED_API, { headers: { Authorization: req.headers.authorization! } });
if (r.status === 401) {
return res.status(401).json({ code: "AUTH_ERROR_401", message: "Unauthorized" });
}
} catch (e) {
next(e);
}
});
Frontend (AG-UI): catch 401 and logout
Use your AG-UI client/middleware observable and intercept HTTP errors with RxJS:
import { catchError, EMPTY } from "rxjs";
agUiStream$
.pipe(
catchError((err) => {
if (err?.status === 401 || err?.response?.status === 401 || err?.code === "AUTH_ERROR_401") {
logout();
return EMPTY;
}
throw err;
})
)
.subscribe();
Why not encode a custom RUN_ERROR code?
- Not supported: the UI currently doesn't expose a dedicated
onError callback or structured codes for RUN_ERROR.
- The provider may swallow raw HTTP responses; surfacing them via middleware
catchError is the advised workaround for now.