package com.lightinit.hsdataplatformresdir.handler;

import com.lightinit.hsdataplatformresdir.common.WebUtilsPro;
import com.lightinit.hsdataplatformresdir.model.ResultState;
import com.lightinit.hsdataplatformresdir.model.ResultStateCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created by WangYao on 2018/5/27.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e, HttpServletRequest request, HttpServletResponse response){
        logger.error(e.getMessage());
        if (WebUtilsPro.isAjaxRequest(request)){
            ResultState resultState = new ResultState();
            resultState.setStateCode(ResultStateCode.UNKNOWN_ERROR);
            resultState.setMsg("系统错误");
            return resultState;
        }
        return new ModelAndView("redirect:error.html");
    }
}
