package com.hwrj.cloud.gateway.config;

import com.hwrj.cloud.common.exception.ApiException;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Map;


public class AbstractExceptionHandler {
    private static long DEFAULT_ERROR_CODE = 500;

    protected String formatMessage(Throwable ex) {

        String errorMessage = null;
        if (ex instanceof NotFoundException) {
            String reason = ((NotFoundException) ex).getMessage();
            errorMessage = reason;
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            errorMessage = responseStatusException.getMessage();
        } else if (ex instanceof ApiException) {
            ApiException exception = (ApiException) ex;
            errorMessage = exception.getMessage();
            DEFAULT_ERROR_CODE = exception.getErrorCode().getCode();
        } else {
            errorMessage = ex.getMessage();
        }
        return errorMessage;
    }

    protected Map<String, Object> buildErrorMap(String errorMessage) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("code", DEFAULT_ERROR_CODE);
        resMap.put("message", errorMessage);
        resMap.put("data", null);
        return resMap;
    }
}
