package com.yeejoin.equipmanage.common.exception.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 全局异常处理器
 * @author: duanwei
 * @create: 2019-08-28 20:07
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    public GlobalExceptionHandler() {
    }

    @ExceptionHandler({Exception.class})
    public ResponseModel<Object> MethodArgumentNotValidHandler(Exception exception) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        ResponseModel<Object> response = new ResponseModel<>();

        //解析平台返回错误信息，统一返回403,app 端统一跳转到登录页面
        if (exception.getMessage() != null && (exception.getMessage().contains("账号已经在其他设备登录") || exception.getMessage().contains("请重新登录"))) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
        } else {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }

        response.setDevMessage("FAILED");
        response.setMessage(exception.getMessage());
        response.setTraceId(RequestContext.getTraceId());
        response.setPath(request.getServletPath());
        exception.printStackTrace();
        return response;
    }

}
