参考: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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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、自定义异常类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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而不是我们自定义的异常类了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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请求的类是从 若依 拷贝出来的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | 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()); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】