Vitron-Front/app/utils/api-error-handler.ts
2026-04-29 01:44:16 +03:30

37 lines
1010 B
TypeScript

/**
* API Error Handler Middleware
* Handles 403 Unauthorized responses by logging out the user
*/
import type { Middleware } from "../../src/api/types/runtime";
/**
* Creates a middleware that handles 403 Unauthorized errors
* When a 403 is detected, it redirects to the logout page
*/
export const createAuthErrorMiddleware = (): Middleware => ({
post: async (context) => {
const response = context.response;
// Check if response is 403 Unauthorized
if (response.status === 403 || response.status === 401) {
console.warn(
"[API Error Handler] 403 Unauthorized detected - logging out user"
);
// Only redirect if we're in browser context
if (typeof window !== "undefined") {
window.location.href = "/logout";
}
}
return response;
},
onError: async (context) => {
// Handle network errors or other fetch errors
console.error("[API Error Handler] Request failed:", context.error);
return context.response;
},
});