package com.chaozhanggui.common.system.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
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.bind.annotation.ResponseStatus;

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

@ControllerAdvice
public class MyExceptionHandler {

    private static final transient Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    /*
     Exception会经历以下三个resolver
     ExceptionHandlerExceptionResolver
     ResponseStatusExceptionResolver
     DefaultHandlerExceptionResolver
     见HandlerExceptionResolverComposite.java 75行。
     如果返回ModelAndView为空，会继续找下一个resolver。

     深度序列化RespBody(Exception e)会有问题：HttpMessageNotWritableException<-HttpMessageNotReadableException<-java.io.PushbackInputStream引起
     见RespBody，只e.getMessage()即可。

     目前跳过RespBody返回的尚有：路径错误。
     */
    @ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentNotValidException.class})
    @ResponseBody
    @ResponseStatus(value = HttpStatus.BAD_REQUEST/*, reason = "输入格式验证失败"*/)//加入reason和status后，则不会返回空的ModelAndView
    RespBody handle1(HttpServletRequest req, HttpServletResponse resp, Exception e) throws Exception {
        logger.error("handleException for BAD_REQUEST", e);
        return new RespBody(e);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    RespBody handle(HttpServletRequest req, HttpServletResponse resp, Exception e) {
        logger.error("handleException for Exception.class", e);
        return new RespBody(e);
    }
}
