参考:https://www.cnblogs.com/lenve/p/10748453.html
http://doc.ruoyi.vip/ruoyi/document/htsc.html#%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86
@ControllerAdvice/@RestControllerAdvice:增强控制器,可以用来做 全局异常处理、全局数据绑定、全局数据预处理。
1、ajax请求异常,返回类AjaxResult

package com.jay.SpringBootStudy8.config;

import java.util.HashMap;

/**
 * 操作消息提醒
 *
 * @author ruoyi
 */
public class AjaxResult extends HashMap<String, Object>
{
    private static final long serialVersionUID = 1L;

    /**
     * 返回错误消息
     *
     * code 错误码
     * msg 内容
     * return 错误消息
     */
    public static AjaxResult error(String msg)
    {
        AjaxResult json = new AjaxResult();
        json.put("msg", msg);
        json.put("code", 500);
        return json;
    }

    /**
     * 返回成功消息
     */
    public static AjaxResult success(String msg)
    {
        AjaxResult json = new AjaxResult();
        json.put("msg", msg);
        json.put("code", 0);
        return json;
    }
}

2、自定义异常类

package com.jay.SpringBootStudy8.config;
/*
自定义异常类
 */
public class CustomerException extends Exception {
    private static final long serialVersionUID = 1L;
    protected final String message;
    public CustomerException(String msg) {
        this.message = msg;
    }
    @Override
    public String getMessage() {
        return message;
    }
}

3、全局异常处理类,其中判断是否是ajax请求,是用请求头信息来判断的,测试的时候注意,这个Handler需要用@RestControllerAdvice标注,使用@ControllerAdvice标注的话,ajax请求返回的是Exception而不是我们自定义的异常类了。

package com.jay.SpringBootStudy8.config;

import com.jay.SpringBootStudy8.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 异常
     */
    @ExceptionHandler(CustomerException.class)
    public Object customerExceptionJson(HttpServletRequest request, CustomerException e)
    {
        String msg = e.getMessage();
        log.error(msg, e);
        if (ServletUtils.isAjaxRequest(request)){
            return AjaxResult.error(msg);
        }
        else{
            ModelAndView mv = new ModelAndView();
            mv.addObject("msg", msg);
            mv.setViewName("/error/500");
            return mv;
        }
    }
}

4、使用:throw new CustomerException("test data");
5、判断是否ajax请求的类是从 若依 拷贝出来的

package com.jay.SpringBootStudy8.utils;

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

import cn.hutool.core.convert.Convert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 客户端工具类
 *
 * @author ruoyi
 */
public class ServletUtils
{
    /**
     * 获取String参数
     */
    public static String getParameter(String name)
    {
        return getRequest().getParameter(name);
    }

    /**
     * 获取String参数
     */
    public static String getParameter(String name, String defaultValue)
    {
        return Convert.toStr(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name)
    {
        return Convert.toInt(getRequest().getParameter(name));
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name, Integer defaultValue)
    {
        return Convert.toInt(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest()
    {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse()
    {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession()
    {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string 待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string)
    {
        try
        {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 是否是Ajax异步请求
     *
     * @param request
     */
    public static boolean isAjaxRequest(HttpServletRequest request)
    {
        String accept = request.getHeader("accept");
        if (accept != null && accept.indexOf("application/json") != -1)
        {
            return true;
        }

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1)
        {
            return true;
        }

        String uri = request.getRequestURI();
        if (inStringIgnoreCase(uri, ".json", ".xml"))
        {
            return true;
        }

        String ajax = request.getParameter("__ajax");
        if (inStringIgnoreCase(ajax, "json", "xml"))
        {
            return true;
        }
        return false;
    }
    //最后这两个方法是从 若依 StringUtils中复制来的
    public static boolean inStringIgnoreCase(String str, String... strs)
    {
        if (str != null && strs != null)
        {
            for (String s : strs)
            {
                if (str.equalsIgnoreCase(trim(s)))
                {
                    return true;
                }
            }
        }
        return false;
    }
    /*
     去空格
     */
    public static String trim(String str)
    {
        return (str == null ? "" : str.trim());
    }
}

  

posted on 2021-08-24 16:02  邢帅杰  阅读(214)  评论(0编辑  收藏  举报