[编辑 输出结果](#编辑 输出结果)
编写全局异常处理类GlobalExceptionHandler
[编辑 异常处理(三)](#编辑 异常处理(三))
一.什么是SpringMVC之JSON返回&异常处理机制
SpringMVC是一个Web框架,它提供了许多方便的特性,其中之一就是JSON返回和异常处理机制。
JSON返回指的是,当客户端向服务器发起请求时,服务器可以返回JSON格式的响应数据。这是非常常见的一种情况,特别是在前后端分离的开发模式中,后端通常会返回JSON格式的数据。
SpringMVC提供了多种方式来实现JSON返回,其中最简单的方式是使用@ResponseBody注解,这个注解可以将Controller方法返回的对象自动转换成JSON格式的数据,然后响应给客户端。如果需要更加灵活的JSON格式化方式,可以使用Jackson或者FastJSON等库进行定制化配置。
异常处理机制指的是当服务器出现异常时,SpringMVC提供了一套通用的异常处理机制,可以统一处理异常,返回友好的错误信息给客户端。在SpringMVC中,异常处理主要分为两种方式,一种是基于@ControllerAdvice注解的全局异常处理方式,另一种是基于@ExceptionHandler注解的局部异常处理方式。通过这两种方式,我们可以针对不同的异常类型进行不同的处理,比如返回特定的错误码、错误信息等。这样可以提高系统的容错性和可靠性。
二.Json处理
导入pom.xml依赖
java
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>xyzy</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>xyzy Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
<!--添加jar包依赖-->
<!--1.spring 5.0.2.RELEASE相关-->
<spring.version>5.0.2.RELEASE</spring.version>
<!--2.mybatis相关-->
<mybatis.version>3.4.5</mybatis.version>
<!--mysql-->
<mysql.version>5.1.44</mysql.version>
<!--pagehelper分页jar依赖-->
<pagehelper.version>5.1.2</pagehelper.version>
<!--mybatis与spring集成jar依赖-->
<mybatis.spring.version>1.3.1</mybatis.spring.version>
<!--3.dbcp2连接池相关 druid-->
<commons.dbcp2.version>2.1.1</commons.dbcp2.version>
<commons.pool2.version>2.4.3</commons.pool2.version>
<!--4.log日志相关-->
<log4j2.version>2.9.1</log4j2.version>
<log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
<slf4j.version>1.7.13</slf4j.version>
<!--5.其他-->
<junit.version>4.12</junit.version>
<servlet.version>4.0.0</servlet.version>
<lombok.version>1.18.2</lombok.version>
<mybatis.ehcache.version>1.1.0</mybatis.ehcache.version>
<ehcache.version>2.10.0</ehcache.version>
<redis.version>2.9.0</redis.version>
<redis.spring.version>1.7.1.RELEASE</redis.spring.version>
<jackson.version>2.9.3</jackson.version>
<jstl.version>1.2</jstl.version>
<standard.version>1.1.2</standard.version>
<tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
<commons-fileupload.version>1.3.3</commons-fileupload.version>
<hibernate-validator.version>5.0.2.Final</hibernate-validator.version>
<shiro.version>1.3.2</shiro.version>
</properties>
<dependencies>
<!--1.spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--2.mybatis相关-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--pagehelper分页插件jar包依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!--mybatis与spring集成jar包依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mybatis与ehcache整合-->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>${mybatis.ehcache.version}</version>
</dependency>
<!--ehcache依赖-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${redis.spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--3.dbcp2连接池相关-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons.dbcp2.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-pool2</artifactId>
<groupId>org.apache.commons</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>${commons.pool2.version}</version>
</dependency>
<!--springmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--4.log日志相关依赖-->
<!-- log4j2日志相关依赖 -->
<!-- log配置:Log4j2 + Slf4j -->
<!-- slf4j核心包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<!--核心log4j2jar包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--用于与slf4j保持桥接-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j2.version}</version>
<scope>runtime</scope>
</dependency>
<!--需要使用log4j2的AsyncLogger需要包含disruptor-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${log4j2.disruptor.version}</version>
</dependency>
<!--5.其他-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<!-- <scope>test</scope>-->
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat-jsp-api.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!--shiro依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
</dependencies>
<build>
<finalName>xyzy</finalName>
<resources>
<!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.properties</include>
<include>*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</build>
</project>
导入Spring-Mvc.xml
java
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
<context:component-scan base-package="com.xy"/>
<!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven />
<!--3) 创建ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--4) 单独处理图片、样式、js等资源 -->
<!-- <mvc:resources location="/css/" mapping="/css/**"/>-->
<!-- <mvc:resources location="/js/" mapping="/js/**"/>-->
<!-- <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>-->
<mvc:resources location="/static/" mapping="/static/**"/>
<!--处理文件的上传下载-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字节) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
<!--配置拦截器-->
<mvc:interceptors>
<bean class="com.xy.interceptor.LoginInterceptor"></bean>
</mvc:interceptors>
<!--2) 多拦截器(拦截器链)-->
<!--<mvc:interceptors>-->
<!--<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.xy.interceptor.OneInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/hpjy/**"/>
<bean class="com.xy.interceptor.TwoInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!--处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!--处理controller层发送请求到biz,会经过切面的拦截处理-->
<aop:aspectj-autoproxy/>
</beans>
编写JsonController
java
package com.xy.web;
import com.xy.biz.hpjyBiz;
import com.xy.biz.hpjyBiz;
import com.xy.model.hpjy;
import com.xy.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author小李飞刀
* @site www.javaxl.com
* @company xxx公司
* @create 2022-08-17 9:41
*/
//@ResponseBody
//@Controller
@RestController
@RequestMapping("/hpjy/json")
public class JsonController {
@Autowired
private hpjyBiz hpjyBiz;
/**
* 返回List<T>
* @param req
* @param hpjy
* @return
*/
// @ResponseBody
@RequestMapping("/list")
public List<hpjy> list(HttpServletRequest req, hpjy hpjy){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<hpjy> lst = this.hpjyBiz.listPager(hpjy, pageBean);
return lst;
}
/**
* 返回T
* @param req
* @param hpjy
* @return
*/
// @ResponseBody
@RequestMapping("/load")
public hpjy load(HttpServletRequest req, hpjy hpjy){
if(hpjy.getId() != null){
List<hpjy> lst = this.hpjyBiz.listPager(hpjy, null);
return lst.get(0);
}
return null;
}
/**
* 返回List<Map>
* @param req
* @param hpjy
* @return
*/
// @ResponseBody
@RequestMapping("/mapList")
public List<Map> mapList(HttpServletRequest req, hpjy hpjy){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map> lst = this.hpjyBiz.mapListPager(hpjy, pageBean);
return lst;
}
/**
* 返回Map
* @param req
* @param hpjy
* @return
*/
// @ResponseBody
@RequestMapping("/mapLoad")
public Map mapLoad(HttpServletRequest req, hpjy hpjy){
if(hpjy.getId() != null){
List<Map> lst = this.hpjyBiz.mapListPager(hpjy, null);
return lst.get(0);
}
return null;
}
// @ResponseBody
@RequestMapping("/all")
public Map all(HttpServletRequest req, hpjy hpjy){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<hpjy> lst = this.hpjyBiz.listPager(hpjy, pageBean);
Map map = new HashMap();
map.put("lst",lst);
map.put("pageBean",pageBean);
return map;
}
// @ResponseBody
@RequestMapping("/jsonStr")
public String jsonStr(HttpServletRequest req, hpjy hpjy){
return "hpjyEdit";
}
}
编写Sql语句
测试结果
// @ResponseBody @RequestMapping("/load") public hpjy load(HttpServletRequest req, hpjy hpjy){ if(hpjy.getId() != null){ List<hpjy> lst = this.hpjyBiz.listPager(hpjy, null); return lst.get(0); } return null; } 测试结果如下:
/** * 返回List<Map> * @param req * @param hpjy * @return */ // @ResponseBody @RequestMapping("/mapList") public List<Map> mapList(HttpServletRequest req, hpjy hpjy){ PageBean pageBean = new PageBean(); pageBean.setRequest(req); List<Map> lst = hpjyBiz.mapListPager(hpjy, pageBean); return lst; }
测试结果如下:
/** * 返回Map * @param req * @param hpjy * @return */ // @ResponseBody @RequestMapping("/mapLoad") public Map mapLoad(HttpServletRequest req, hpjy hpjy){ if(hpjy.getId() != null){ List<Map> lst = this.hpjyBiz.mapListPager(hpjy, null); return lst.get(0); } return null; }
测试结果如下:
// @ResponseBody @RequestMapping("/all") public Map all(HttpServletRequest req, hpjy hpjy){ PageBean pageBean = new PageBean(); pageBean.setRequest(req); List<hpjy> lst = this.hpjyBiz.listPager(hpjy, pageBean); Map map = new HashMap(); map.put("lst",lst); map.put("pageBean",pageBean); return map; }
测试结果如下:
// @ResponseBody @RequestMapping("/jsonStr") public String jsonStr(HttpServletRequest req, hpjy hpjy){ return "hpjyEdit"; } 测试结果如下:
json转换的注解
测试结果(@JsonIgnore)
(注:隐藏想要隐藏的)
三.全局异常处理机制
为什么要全局异常处理
我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。
异常处理思路
自写一个错误代码
输出结果
异常处理方式(一)
在Spring-Mvc.xml中写异常处理方式
新建一个erreo.jsp
(注:获取异常的xx)
输出结果
异常处理(二)
编写GlobalException类
java
package com.xy.exception;
public class GlobalException extends RuntimeException {
public GlobalException() {
}
public GlobalException(String message) {
super(message);
}
public GlobalException(String message, Throwable cause) {
super(message, cause);
}
public GlobalException(Throwable cause) {
super(cause);
}
public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
编写全局异常处理类GlobalExceptionHandler
java
package com.xy.component;
import com.xy.exception.GlobalException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//全局异常处理类
@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) {
ModelAndView mv = new ModelAndView();
mv.setViewName("error");
if (e instanceof GlobalException){
GlobalException globalException = (GlobalException) e;
mv.addObject("ex",globalException.getMessage());
mv.addObject("msg","全局异常....");
}else if (e instanceof RuntimeException){
RuntimeException runtimeException = (RuntimeException) e;
mv.addObject("ex",runtimeException.getMessage());
mv.addObject("msg","运行时异常....");
}else {
mv.addObject("ex",e.getMessage());
mv.addObject("msg","其他异常....");
}
return mv;
}
}
在error.jsp中编写
在JsonController类编写异常
测试结果
异常处理(三)
编写GlobalExceptionResolver类
java
package com.xy.component;
import com.xy.exception.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionResolver {
// 返回错误json数据
@ResponseBody
@ExceptionHandler
public Map handler(Exception e){
Map map = new HashMap();
if (e instanceof GlobalException){
GlobalException globalException = (GlobalException) e;
map.put("ex",globalException.getMessage());
map.put("msg","全局异常....");
}else if (e instanceof RuntimeException){
RuntimeException runtimeException = (RuntimeException) e;
map.put("ex",runtimeException.getMessage());
map.put("msg","运行时异常....");
}else {
map.put("ex",e.getMessage());
map.put("msg","其它异常....");
}
return map;
}
测试结果
重新编写GlobalExceptionResolver类
java
package com.xy.component;
import com.xy.exception.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionResolver {
// 跳转错误页面
@ExceptionHandler
public ModelAndView handler(Exception e) {
ModelAndView mv = new ModelAndView();
mv.setViewName("error");
if (e instanceof GlobalException) {
GlobalException globalException = (GlobalException) e;
mv.addObject("ex", globalException.getMessage());
mv.addObject("msg", "全局异常....");
} else if (e instanceof RuntimeException) {
RuntimeException runtimeException = (RuntimeException) e;
mv.addObject("ex", runtimeException.getMessage());
mv.addObject("msg", "运行时异常....");
}
return mv;
}