博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMVC实现全局异常捕获处理
阅读量:7106 次
发布时间:2019-06-28

本文共 4763 字,大约阅读时间需要 15 分钟。

需求:在SpringMVC中实现全局异常捕获解析以及处理并且返回json状态码

需求分析解决:
1、进入Spring-MVC配置文件配置全局异常处理

复制代码

2、定义全局异常处理类

import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;import com.xxx.bean.Result;import com.xxx.excption.CustomException;import com.xxx.util.ResultUtils;/** * 全局异常处理器 * @author CatalpaFlat */public class CustomExceptionResolver implements HandlerExceptionResolver{      /**日志log*/    private static Logger log = LoggerFactory.getLogger(CustomExceptionResolver.class);    //系统抛出的异常      @Override      public ModelAndView resolveException(HttpServletRequest request,              HttpServletResponse response, Object handler, Exception ex) {          //handler就是处理器适配器要执行的Handler对象(只有method)          //解析出异常类型。          /*  使用response返回    */          response.setStatus(HttpStatus.OK.value()); //设置状态码          response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType          response.setCharacterEncoding("UTF-8"); //避免乱码          response.setHeader("Cache-Control", "no-cache, must-revalidate");          //如果该 异常类型是系统 自定义的异常,直接取出异常信息。          CustomException customException=null;          try {            if(ex instanceof CustomException){                  customException = (CustomException)ex;                  //错误信息                  response.getWriter().write(ResultUtils.error(customException.getCode(),ex.getMessage()).toString());            }else                response.getWriter().write(ResultUtils.error(-1,ex.getMessage()).toString());        } catch (IOException e) {            log.error("与客户端通讯异常:"+ e.getMessage(), e);              e.printStackTrace();        }        ModelAndView modelAndView=new ModelAndView();          return modelAndView;      }  }复制代码

3、自定义异常类CustomException

import com.xxx.enums.ResultEnum;/** * 自定义异常类型 * @author CatalpaFlat */public class CustomException extends Exception {    private Integer code;    public CustomException(){}    public CustomException(ResultEnum resultEnum) {        super((resultEnum.getMsg()));        this.code = resultEnum.getCode();    }    public Integer getCode() {        return code;    }    public void setCode(Integer code) {        this.code = code;    }}复制代码

4、定义Http响应json类

/**  * http请求返回的最外层 * Created by CatalpaFlat  * on 2017/4/12. */public class Result
{ private Integer code; private String msg; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return "{\"code\": "+code+",\"msg\": \""+msg+"\",\"data\": "+data+"}"; }}复制代码

5、定义http返回json的ResulUtils

import com.xxx.bean.Result;/**  * http请求返回success以及error方法封装 * Created by CatalpaFlat  * on 2017/4/12. */public class ResultUtils {    private static final String SUCCESS_MSG = "成功";    /**     * http回调成功     * @param object     * @return     */    public  static Result success(Object object){        Result result = new Result();        result.setCode(1);        result.setMsg(SUCCESS_MSG);        result.setData(object);        return result;    }    /**     * 无object返回     * @return     */    public  static Result success(){        return success(null);    }    /**     * http回调错误     * @param code     * @param msg     * @return     */    public static Result error(Integer code,String msg){        Result result = new Result();        result.setCode(code);        result.setMsg(msg);        return  result;    }}复制代码

6、定义异常类型枚举ResultEnum

/** * 枚举定义异常类型以及相对于的错误信息 * 有助于返回码的唯一性 * Created by CatalpaFlat   * on 2017/4/12. */public enum ResultEnum {    UNKONW_ERROR(-1,"未知错误"),    SUCCESS(0,"成功"),    TEST_ERRORR(100,"测试异常");    private Integer code;    private String msg;    ResultEnum(Integer code,String msg){        this.code = code;        this.msg = msg;    }    public Integer getCode() {        return code;    }    public String getMsg() {        return msg;    }}复制代码

7、测试TestController

@Controller@RequestMapping("/teco")public class TestController {    @RequestMapping(value = "/testexc",method = RequestMethod.GET)    @ResponseBody    public void testException() throws CustomException{        throw new CustomException(ResultEnum.TEST_ERRORR);    }}复制代码

8、测试接口json返回

转载地址:http://qtvhl.baihongyu.com/

你可能感兴趣的文章
Python 字典常用操作
查看>>
tomcat+nginx+shiro+jfinal 实现负载均衡,session共享
查看>>
深入Java虚拟机之虚拟机体系结构
查看>>
Bitcoin的解决的一个核心问题是什么
查看>>
java NIO2(file io)
查看>>
【读书笔记】06 | 白话容器基础(二):隔离与限制
查看>>
Django 学习笔记(二)
查看>>
Linux系统的grep以及正则表达式浅析!
查看>>
Orange的扩展插件Widgets开发(七)-GUI Control
查看>>
用python实现银行转账功能
查看>>
python学习笔记---列表
查看>>
Decorator 装饰器小记
查看>>
Centos6.5搭建Wiki
查看>>
linux 清空文件内容的方法
查看>>
2018“硅谷技划”随笔(三):人工智能火热背后的真正温度
查看>>
综合技术 --ORM
查看>>
我的友情链接
查看>>
[C++]STL萃取学习
查看>>
httpClient学习
查看>>
函数指针和指针函数的区别
查看>>