All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.whosly.disclosure.early.handler.ErrorHandlerFactory Maven / Gradle / Ivy

package com.whosly.disclosure.early.handler;

import com.whosly.disclosure.early.handler.spi.ErrorHandler;
import com.whosly.disclosure.early.handler.spi.exception.ConfigurationException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * error handler factory.
 *
 * @author fengyang 
 * @date 2020-10-09  13:14
 * @title: ErrorHandlerFactory
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ErrorHandlerFactory {

    private static final Map HANDLERS = new LinkedHashMap<>();

    private static final String DEFAULT_HANDLER = ErrorGeneralHandlerType.LOG.name();

    static {
        // 每次 ServiceLoader.load 都会获取到一次实例。
        for (ErrorHandler each : ServiceLoader.load(ErrorHandler.class)) {
            // 加入本地缓存中,便于后续直接使用
            HANDLERS.put(each.getType(), each);
        }
    }

    /**
     * Get error handler.
     *
     * @param type error handler type
     * @return error handler
     */
    public static ErrorHandler getHandler(final ErrorGeneralHandlerType type) {
        if (type == null) {
            return HANDLERS.get(DEFAULT_HANDLER);
        }
        if (!HANDLERS.containsKey(type.name())) {
            throw new ConfigurationException("Can not find error handler type '%s'.", type);
        }
        return HANDLERS.get(type.name());
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy