package cn.hnthyy.thmz.interceptor;


import cn.hnthyy.thmz.entity.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 全局异常处理器
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = AuthException.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, AuthException ex){
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        System.out.println("=====================全局异常信息捕获=======================");
        String  msg= ex.getMessage();
        log.error(ex.toString());
        if(StringUtils.isBlank(msg)){
            msg = "操作异常!";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(msg);
        } catch(Exception e){
            e.printStackTrace();
        } finally {
            if(out!=null){

            }
        }
        return null;
    }
}