package cn.quant.baa.pay.support;

import cn.quant.spring.ExceptionEnum;
import cn.quant.spring.ServerRuntimeException;
import cn.quant.spring.context.ContextLoader;
import cn.quant.spring.context.ServerApplicationContext;
import cn.quant.spring.http.HttpResponseData;
import cn.quant.spring.web.annotation.JsonpMapping;
import cn.quant.spring.web.support.JsonpResponseAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * <p><b>Enable Exception Advice Annotation:</b><br/>
 * <code>@org.springframework.web.bind.annotation.RestControllerAdvice</code>
 * </p>
 * @date 2018-04-09 11:01
 **/
@RestControllerAdvice
public class ExceptionAdvice {

    private static final Logger log = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public HttpResponseData handlerException(HttpServletRequest request, Exception e) {

        log.error("!!- Exception request url - {} ", request.getRequestURI(), e);

        String message = e.getMessage();
        HttpResponseData responseData = new HttpResponseData(e);
        if ((message == null) && ServerRuntimeException.class.isInstance(e)) {
            ServerRuntimeException exception = (ServerRuntimeException) e;
            ExceptionEnum type = exception.getType();
            if (type != null) {
                ServerApplicationContext applicationContext = ContextLoader.getCurrentApplicationContext();
                message = applicationContext.getMessage(type.MESSAGE_CODE);
                responseData.setMessage(message);
                responseData.setStatus(type.ERROR_CODE);
            }
        }
        return responseData;
    }
}