package com.mortals.xhx.base.framework.exception;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一异常处理
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandle {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;


    public static final String KEY_RESULT_CODE = "code";
    public static final String KEY_RESULT_MSG = "msg";
    public static final String KEY_RESULT_DATA = "data";
    public static final int VALUE_RESULT_FAILURE = -1;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String handle(Exception e) {
        JSONObject ret = new JSONObject();
        ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
        if (e instanceof AppException) {
            StackTraceElement stack = e.getStackTrace()[0];
            log.error("[business error]=========stack message[{}],[{},method:{},line{}][{}]", e.getMessage(),
                    stack.getClassName(), stack.getMethodName(), stack.getLineNumber(), e.getClass().getName());
            AppException ex = (AppException) e;
            ret.put(KEY_RESULT_MSG, ex.getMessage());
        }
        if (e instanceof HttpMessageNotReadableException) {
            log.error("[system error]", e);
            response.setStatus(HttpStatus.HTTP_BAD_REQUEST);
            ret.put(KEY_RESULT_MSG, "参数错误，"+ StrUtil.subBefore(e.getMessage(), ";", false));
        } else {
            log.error("[system error]", e);
            response.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);
            ret.put(KEY_RESULT_MSG, "未知错误!" + e.getMessage());
        }
        return ret.toJSONString();
    }
}
