API Error response handling
This provides a centralized way to handle API errors by extracting status codes, mapping them to user-friendly messages, and managing session expirations. It ensures consistent error handling across the application.
The composable maintains two reactive state variables: error, which stores the error message, and statusCode, which holds the HTTP status code. These values are updated whenever an error occurs.
The handleError function processes API errors by extracting the status code from the response. It then assigns an appropriate message from a predefined list or uses the original message for specific errors like 409, 498, 423, 429, and 422. If the error is 401 (Unauthorized), the function clears local storage and redirects the user to the login page with a session expiration message.
The clearError function resets both error and statusCode to null, allowing for error state management.
To use this composable, call handleError(err) whenever an API request fails, and use clearError() when you need to reset the error state.
Example Structure
Add to composables/error.js
// composables/error.js
import { ref } from 'vue'
export function useErrorHandler() {
const error = ref(null)
const statusCode = ref(null)
const statusMessages = {
400: 'Please check your input and try again.',
409: 'Conflict error. Please try again later.',
498: 'Invalid token. Please log in again.',
423: 'Resource is locked. Please try again later.',
429: 'Too many requests. Please try again later.',
422: 'Unprocessable entity. Please check your input.',
default: 'An unexpected error occurred. Please try again.',
}
function handleError(err) {
const errorResponse = err.response || err
statusCode.value = errorResponse.status || 500
error.value = statusMessages[statusCode.value] || errorResponse.message || statusMessages.default
if (statusCode.value === 401) {
localStorage.clear()
window.location.href = '/login?message=session-expired'
}
// Handle 409 with original message
if (statusCode.value === 409 && errorResponse.message) {
error.value = errorResponse.message;
} else {
error.value = errorResponse.message ? statusMessages[statusCode.value] || statusMessages.default : statusMessages.default;
}
return { error: error.value, statusCode: statusCode.value }
}
function clearError() {
error.value = null
statusCode.value = null
}
return { error, statusCode, handleError, clearError }
}