Spring MVC 全局异常处理
Sprng MVC 的全局异常异常处理有很多种方法,这里写一个个人认为最好用的,最清晰,最容易实现的方式,就是自定义全局异常处理器,其余方式可参考https://blog.csdn.net/eson_15/article/details/51731567,有较为全面的讲解。
这里实现的自定义全局处理分为两种方式,一种是跳转至错误页面的方式,一种返回json格式的错误信息。
一.返回错误页面
1.自定义错误类
package com.lzl.compoent; public class CustomException extends Exception{ /** * */ private static final long serialVersionUID = 1L; private String errorMessage; public CustomException(String errorMessage) { super(); this.errorMessage = errorMessage; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
2.实现全局异常处理接口
package com.lzl.compoent; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; @Component public class CustomExceptionResolver implements HandlerExceptionResolver{ @Override public ModelAndView resolveException(HttpServletRequest resquest, HttpServletResponse response, Object obj, Exception exception) { // TODO Auto-generated method stub exception.printStackTrace(); CustomException customException = null; if(exception instanceof CustomException){ customException = (CustomException) exception; }else { customException = new CustomException(exception.getMessage()); } ModelAndView mv = new ModelAndView(); mv.addObject("errorMessage",customException.getErrorMessage() ); mv.setViewName("error"); return mv; } }
3.建立错误信息页面
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> 哎呀,出错了!错误信息:${errorMessage} </body> </html>
4.在方法中抛出自定义的异常
@RequestMapping("/insertUser") @ResponseBody public String insertUser() throws Exception{ UserInfo user = new UserInfo(); user.setUserName("李思"); user.setAge(19); user.setSex("2"); Integer i = userService.insertUser(user); if(1==i){ //int x=i/0; throw new CustomException("系统异常,请稍候重试!"); } return "success"+i; }
5.结果
二、返回json格式的错误信息,实现方式和上面是一致的,只不过是输出结果不同
1.首先新建自定义异常对象
package com.lzl.compoent; public class BusException extends Exception{ /** * */ private static final long serialVersionUID = 1L; private String errorCode; private String errorMessage; public BusException(String errorCode, String errorMessage) { super(); this.errorCode = errorCode; this.errorMessage = errorMessage; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
2..实现全局异常处理接口,并将错误结果输出
package com.lzl.compoent; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSON; @Component public class BusExceptionResolver implements HandlerExceptionResolver{ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object hanObject, Exception exception) { ModelAndView mv = new ModelAndView(); exception.printStackTrace(); BusException busException = null; Map<String, Object> map = new HashMap<String, Object>(); if(exception instanceof BusException){ busException = (BusException) exception; map.put("code", busException.getErrorCode()); map.put("message", busException.getErrorMessage()); }else{ map.put("code", "500"); map.put("message", exception.getMessage()); } response.addHeader("Content-Type", "application/json;chaset=UTF-8"); try { response.getOutputStream().write(JSON.toJSONBytes(map)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mv; } }
3.抛出自定义异常
@RequestMapping("/insertUser") @ResponseBody public String insertUser() throws Exception{ UserInfo user = new UserInfo(); user.setUserName("李思"); user.setAge(19); user.setSex("2"); Integer i = userService.insertUser(user); if(1==i){ //int x=i/0; throw new BusException("100","系统异常,请稍候重试!"); } return "success"+i; }
4.运行结果
最后,特别说明:实现全局异常处理接口的类必须被注入到spring MVC 中,我这里在spring MVC 的配置文件中通过 <context:component-scan base-package="com.lzl.compoent"/> 将 全局异常接口的实现类所在的包放在了spring mvc 自动扫描的路径下,通过@Component注解实现自动注入的,否则则需要在spring MVC 的配置文件中手动配置bean。