package com.nbclass.exception;

import com.alibaba.fastjson.JSONObject;
import com.nbclass.util.CoreConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 实现spring注解进行异常统一处理
 * @author Leon
 * @datetime 2019年3月5日 下午6:08:54
 */
@ControllerAdvice
public class CommonExceptionAdvice {

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


	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(Exception.class)
	//@ResponseBody
	public void defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try {
			logger.info("RequestURL = "+request.getRequestURL());
			String error = exception.getMessage();
			if(exception instanceof ParameterException || exception instanceof ServiceException || exception instanceof LogicalException){
				logger.info(exception.toString());
			}else if(exception instanceof NullPointerException){
				error = "网络异常，请稍候再试~";
			}else{
				if(StringUtils.isBlank(error))error="网络异常，请稍候再试！";
				logger.error("系统异常: ", exception);
			}

			PrintWriter out = response.getWriter();
			JSONObject json = new JSONObject();
			json.put(CoreConst.STATUS, CoreConst.STATUS_ERROR);
			json.put(CoreConst.MSG, error);
			out.print(json.toString());

			/*
			if(StringUtils.isBlank(error)){
				response.setHeader("Content-Type", "text/html;charset=UTF-8");
	            out.print("<div style=\"width:100%;margin-top:20px;text-align:center;\">Sorry, System error !</div>");
			}else{
				JSONObject json = new JSONObject();
	        	json.put(CoreConst.STATUS, CoreConst.STATUS_ERROR);
	        	json.put(CoreConst.MSG, error);
	            out.print(json.toString());
			}
			*/

            out.flush();
            out.close();
        } catch (IOException e) {
        	logger.error("统一处理异常错误", e);
        }
	}
	
    @ExceptionHandler(AuthorizationException.class)
    public String handleAuth(HttpServletRequest request) {
        request.setAttribute("javax.servlet.error.status_code",com.nbclass.enums.ResponseStatus.FORBIDDEN.getCode());
        return "forward:/error";
    }
	
}

