SpringMVC实现全局异常捕获处理

需求:在SpringMVC中实现全局异常捕获解析以及处理并且返回json状态码
需求分析解决:
1、进入Spring-MVC配置文件配置全局异常处理

     <!-- 全局异常处理  自定义实现spring的全局异常解析器HandlerExceptionResolver -->
    <bean id="exceptionResolver" class="com.xxx.resolver.CustomExceptionResolver"></bean>复制代码

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<T> {
    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返回

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值