package com.xhkjedu.gateway.advice;

import com.google.common.base.Throwables;
import com.xhkjedu.gateway.exceptions.GatewayException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

import java.net.ConnectException;

/**
 * @Description 这个不是SpringMVC统一异常处理（具体说明详见：ExceptionHandlerCore）
 * @Author: YWX
 * @Date 2023/11/15 17:52
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlerAdvice {

    @ExceptionHandler(GatewayException.class)
    public ResultVo handler(GatewayException e) {
        return new ResultVo(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(ResponseStatusException.class)
    public ResultVo handler(ResponseStatusException e) {
        return new ResultVo(1, e.getReason());
    }

    @ExceptionHandler(ConnectException.class)
    public ResultVo handler(ConnectException e) {
        log.error(Throwables.getStackTraceAsString(e));
        return new ResultVo(1, "网络异常,请稍候再试!");
    }

    @ExceptionHandler(Throwable.class)
    public ResultVo handler(Throwable e) {
        log.error(Throwables.getStackTraceAsString(e));
        return new ResultVo(1, "服务器异常");
    }

}

@Data
@AllArgsConstructor
class ResultVo{
    private Integer code;// 返回是否成功  0成功 1失败
    private String msg;// 返回提示信息
    private Object obj;// 返回对象或者对象列表

    public ResultVo(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}
