package com.ruoyi.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.web.util.NestedServletException;

import javax.servlet.*;
import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;

@Component
public class GlobalExceptionHandlerFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        try {
            filterChain.doFilter(servletRequest,servletResponse);
        }catch (Exception e){
            /**
             * 捕捉出现的异常，根据自己的需求进行处理
             * ResultEntity 自定义的响应结果封装类
             * SCSException 自定义异常
             */
            servletResponse.setCharacterEncoding("UTF-8");
            AjaxResult ajaxResult = null;
            Throwable throwable;
            if(e instanceof NestedServletException){
                throwable = e.getCause();
            }else{
                throwable = e;
            }
            /**
             * 重复数据异常
             */

            if(throwable instanceof DuplicateKeyException){
                ajaxResult = AjaxResult.error("该数据已经存在");
            }else if(throwable instanceof SQLIntegrityConstraintViolationException){
                ajaxResult = AjaxResult.error("该数据已经存在");
            }else if(throwable instanceof ServiceException){
                ajaxResult = AjaxResult.error(e.getMessage());
            }else{
                throw e;
            }
            servletResponse.getWriter().write(JSONObject.toJSONString(ajaxResult));
        }
    }
}
