package com.diaoyun.zion.master.exception;

import com.alibaba.fastjson.JSON;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 统一异常处理
 * 
 * @author Joe
 */
//@Component("exceptionResolver")
@Deprecated
public class ExceptionResolver implements HandlerExceptionResolver {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception exception) {
		Result result = null;
		if (exception instanceof ApplicationException) {
			ApplicationException ae = (ApplicationException) exception;
			result = new Result(ae.getCode(),ae.getMessage());
		}
		else {
			result = new Result(ResultCodeEnum.ERROR.getCode(),exception.getMessage());
			logger.error(exception.getMessage(), exception);
		}

		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(HttpStatus.OK.value());
        PrintWriter writer=null;
		try {
			writer = response.getWriter();
			writer.write(JSON.toJSONString(result));

		}
		catch (IOException ie) {
			logger.error("Failed to serialize the object to json for exception resolver!", ie);
		} finally {
            writer.flush();
            writer.close();
		}
		return new ModelAndView();
	}
}
