package work.zhili.springboot2template.handler;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
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.util.HashMap;
import java.util.Map;

/**
 * Title : work.zhili.springboot2template.handler <br>
 * Description :
 *  <p>
 *  <ul> 
 *      <li>
 *  </ul>
 * @author chile
 * @version 1.0
 * @date 2018/3/21 18:19
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

    /**
     * the logger, get from slf4j
     */
    private static Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    private static String API = "api";

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                         Object o, Exception e) {

        logger.error("ExceptionHandler caught exception : ", e);

        String requestType = httpServletRequest.getHeader("X-Requested-With");

        if (API.equals(requestType)) {
            // JSON格式返回
            Map<String, Object> responseMap = new HashMap<>(2);
            responseMap.put("code", -1);
            responseMap.put("msg", "System is not available, please try it later.");
            responseMap.put("result", new HashMap<>(0));
            String json = new Gson().toJson(responseMap);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            try {
                httpServletResponse.getWriter().write(json);
                httpServletResponse.getWriter().flush();
                return null;
            } catch (IOException ee) {
                logger.error("", ee);
            }
        }

        return new ModelAndView("redirect:/500.html");
    }
}

@@ -909,48 +909,8 @@
 );%0A%0A
-    private static String API = %22api%22;%0A%0A
     
@@ -1169,24 +1169,76 @@
 n : %22, e);%0A%0A
+        // ajax requests always contain this header%0A
         Stri
@@ -1321,18 +1321,28 @@
 if (
-API.equals
+!StringUtils.isEmpty
 (req
@@ -1373,16 +1373,21 @@
  // 
-JSON%E6%A0%BC%E5%BC%8F%E8%BF%94%E5%9B%9E
+return a json
 %0A   

add comment