package com.github.wxiaoqi.security.common.handler;


import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.BaseResponse;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice("com.xxfc.platform")
@Slf4j
public class PlatformExceptionHandler {

    @ExceptionHandler(value = {BaseException.class})
    public BaseResponse baseExceptionHandler(Exception e) {
        if (e instanceof BaseException){
             BaseException be = (BaseException) e;
            return new BaseResponse(be.getStatus(), be.getMessage());
        }
        return new BaseResponse(400,e.getMessage());
    }

    //服务器异常
    @ExceptionHandler(Exception.class)
    public ObjectRestResponse<?> exceptionHandler(Exception e){
        Throwable cause = e.getCause();
        if(cause != null && cause.toString().contains("Exception")) {
            log.error(cause.getMessage(), e);
            return assembleResult(ObjectRestResponse.createFailedResult(5000, "服务器开小差了，请稍后重试！"), "Server exception: " + e.getMessage());
        }
        log.error("Server exception: ", e);
        return assembleResult(ObjectRestResponse.createFailedResult(5000, "服务器开小差了，请稍后重试！"), "Server exception: " + e.getMessage());
    }

    protected ObjectRestResponse<?> assembleResult(ObjectRestResponse<?> error, String msg) {
        log.debug("Exception: " + msg);
        return error;
    }

    protected ObjectRestResponse<?> assembleResult(ObjectRestResponse<?> error, Throwable e) {
        return assembleResult(error, e.getClass().getSimpleName() + ": " + e.getMessage());
    }

}
