如何构建一个权限项目这里接着我们上次说的来编写代码,我们这个点主要讲的是接口请求全局异常处理,
接下来跟我一起看我编写的代码如何实现的,首先我们要定义一个全局异常的处理类,在common包下建一个类SpringExceptionResolver:
package cn.oyc.common; import cn.oyc.exception.ParamException; import cn.oyc.exception.PermissionException; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Slf4j public class SpringExceptionResolver implements HandlerExceptionResolver { private final Logger logger = LoggerFactory.getLogger(SpringExceptionResolver.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) { String url = request.getRequestURL().toString(); ModelAndView mv; String defaultMsg = "System error"; // 这里我们要求项目中所有请求json数据,都是用.json结尾 if (url.endsWith(".json")){ if (ex instanceof PermissionException || ex instanceof ParamException){ JsonData result = JsonData.fail(ex.getMessage()); mv = new ModelAndView("jsonView",result.toMap()); }else{ logger.error("unknown json exception, url:"+url,ex); JsonData result = JsonData.fail(defaultMsg); mv = new ModelAndView("jsonView",result.toMap()); } }else if (url.endsWith(".page")){ // 这里我们要求项目中所有请求page页面,都是用.page结尾 logger.error("unknown exception, url:"+url,ex); JsonData result = JsonData.fail(defaultMsg); mv = new ModelAndView("exception",result.toMap()); }else{ logger.error("unknown exception, url:"+url,ex); JsonData result = JsonData.fail(defaultMsg); mv = new ModelAndView("jsonView",result.toMap()); } return mv; } }
在这些代码的基础下我们还需要在pom文件导入相关依赖,相关依赖如下:
<!--jsp api--> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>jsp-api</artifactId> <version>6.0.36</version> </dependency>
还需要定义我们自己的异常,建立一个exception包,然后建一个PermissionException类:
package cn.oyc.exception; /** * 自己定义的异常类 * */ public class PermissionException extends RuntimeException { public PermissionException() { super(); } public PermissionException(String message) { super(message); } public PermissionException(String message, Throwable cause) { super(message, cause); } public PermissionException(Throwable cause) { super(cause); } protected PermissionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
我们的定义的一个全局异常如果page出现异常找的execption需要我们在views文件夹下创建一个execption.jsp文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Exception</title> </head> <body> </body> </html>
这里我们先不做请求,等后续在完善
然后在我们的spring-servlet.xml下加上一个bean:
<bean class="cn.oyc.common.SpringExceptionResolver"/>
我们的接口请求全局异常处理就讲到这里后续请关注下一章
原文地址:https://www.cnblogs.com/Myoyc/p/12231464.html
时间: 2024-11-05 22:44:10