Publish Fast Tabler Docker image / build-and-push-fast (push) Successful in 1m43s
83 lines
2.2 KiB
JavaScript
83 lines
2.2 KiB
JavaScript
import { useCallback } from 'react';
|
|
import { useNotify } from '../components/NotifyProvider';
|
|
import { formatErrorMessage, getErrorAction, getErrorDetails } from '../lib/api';
|
|
|
|
/**
|
|
* useErrorHandler - хук для обработки ошибок в компонентах
|
|
* Предоставляет единообразный способ обработки ошибок
|
|
*/
|
|
export function useErrorHandler() {
|
|
const notify = useNotify();
|
|
|
|
const handleError = useCallback((error, context = {}) => {
|
|
console.error('Error in component:', error, context);
|
|
|
|
const message = formatErrorMessage(error);
|
|
const action = getErrorAction(error);
|
|
const details = getErrorDetails(error);
|
|
|
|
notify.error(message, {
|
|
...details,
|
|
action,
|
|
context
|
|
});
|
|
}, [notify]);
|
|
|
|
const handleSuccess = useCallback((message = 'Операция выполнена успешно') => {
|
|
notify.success(message);
|
|
}, [notify]);
|
|
|
|
const handleWarning = useCallback((message, details) => {
|
|
notify.warning(message, details);
|
|
}, [notify]);
|
|
|
|
const handleInfo = useCallback((message, details) => {
|
|
notify.info(message, details);
|
|
}, [notify]);
|
|
|
|
// Обёртка для async функций с автоматической обработкой ошибок
|
|
const withErrorHandler = useCallback((asyncFn, options = {}) => {
|
|
return async (...args) => {
|
|
try {
|
|
const result = await asyncFn(...args);
|
|
|
|
if (options.successMessage) {
|
|
handleSuccess(options.successMessage);
|
|
}
|
|
|
|
return result;
|
|
} catch (error) {
|
|
if (!options.silent) {
|
|
handleError(error, options.context);
|
|
}
|
|
|
|
if (options.rethrow) {
|
|
throw error;
|
|
}
|
|
|
|
return options.defaultValue;
|
|
}
|
|
};
|
|
}, [handleError, handleSuccess]);
|
|
|
|
return {
|
|
handleError,
|
|
handleSuccess,
|
|
handleWarning,
|
|
handleInfo,
|
|
withErrorHandler
|
|
};
|
|
}
|
|
|
|
/**
|
|
* useAsyncError - хук для обработки async ошибок в useEffect
|
|
*/
|
|
export function useAsyncError() {
|
|
const { handleError } = useErrorHandler();
|
|
|
|
return useCallback((promise, context) => {
|
|
promise.catch(error => handleError(error, context));
|
|
}, [handleError]);
|
|
}
|
|
|