天天看点

spring mvc (返回json)的异常统一处理

 定义一个项目业务异常的超类

/**
 * @Title:BusinessException
 * @Description:Comment for created type
 * @author 张颖辉
 * @date 2018年3月16日下午5:13:56
 * @version 1.0
 */
public class BusinessException extends RuntimeException {

	/**
	 * @Title:字段属性 serialVersionUID
	 * @Description:Comment for fields
	 * @author 张颖辉
	 * @date 2018年3月16日下午5:14:20
	 */
	private static final long serialVersionUID = 1L;
	/** 错误码 **/
	private Integer errorCode;
	/** 错误消息 **/
	private String errorMsg;

	public BusinessException(Integer errorCode, String errorMsg) {
		super(errorMsg);
		this.errorCode = errorCode;
		this.errorMsg = errorMsg;
	}

	public Integer getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(Integer errorCode) {
		this.errorCode = errorCode;
	}

	public String getErrorMsg() {
		return errorMsg;
	}
}
           

所有返回json的Controller的超类 

package org.rgdata.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.rgdata.common.JsonResult;
import org.rgdata.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * @Title:日志初始化,以及异常统一处理
 * @Description:Comment for created type
 * @author 张颖辉
 * @date 2017年9月27日上午9:49:33
 * @version 1.0
 */
public class BaseController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler
	@ResponseBody
	public JsonResult<String> handleAndReturnData(HttpServletRequest request, HttpServletResponse response,
			Exception ex) {
		if (ex instanceof BusinessException) {
			BusinessException e = (BusinessException) ex;
			return JsonResult.createByErrorCodeMessage(e.getErrorCode(), e.getMessage());
		}
		return JsonResult.createByErrorMessage("系统异常 "+ex.getClass().getName()+":"+ex.getMessage());
	}
}
           

使用示例:在controller的函数中使用类似下面的方法,业务异常因为是运行时异常,所以也可以在service或者dao层抛出,都会被捕捉处理

/**
	 * @Title: 获取一场比赛/训练 的视频列表
	 * @Description:Comment for non-overriding methods
	 * @author 张颖辉
	 * @date 2018年3月16日下午1:21:08
	 * @param wxSession
	 * @return
	 */
	@RequestMapping(value = "/getVideoByMatchIdOrTrainId")
	@ResponseBody
	public JsonResult<Map<String, Object>> getVideoByMatchIdOrTrainId(String wxSession, String nomodeId,
			Integer pageNum, Integer pageSize, HttpServletRequest request) {
		if (1==1) {
			throw new BusinessException(ResultCode.NEED_LOGIN.getCode(), "需要登陆");
		}
		pageNum = pageNum == null ? 1 : pageNum;
		pageSize = pageSize == null ? 10 : pageSize;
		return wq4WeixinService.getVideoByMatchIdOrTrainId(wxSession,nomodeId, pageNum, pageSize, request);

	}
           

其中JsonResult以及ResultCode的源码:springMVC Json返回的封装

测试返回:

spring mvc (返回json)的异常统一处理

版权声明:本文为CSDN博主「weixin_34132768」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/weixin_34132768/article/details/91948080