您的位置:首页 > 编程语言 > Java开发

SpringMVC为controller错误做统一处理

2017-03-11 00:00 501 查看
1 项目中经常出现遇到RuntimeException,需要给出一个默认返回JSON

2 使用 @ControllerAdvice,不用任何的配置,只要把这个类放在项目中,Spring能扫描到的地方。就可以实现全局异常的回调。

代码如下:

package cc.messcat.common.exception;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.util.LogUtil;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;

@ControllerAdvice
public class WebExceptionHandler{
/**
* 全局处理Exception
* 错误的情况下返回500
* @param ex
* @param req
* @return
*/
@ExceptionHandler(value = {Exception.class})
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
HandlerMethod hm = (HandlerMethod) handler;
String className = hm.getBeanType().getSimpleName();
String method = hm.getMethod().getName();
StringBuffer buffer = new StringBuffer(className);
buffer.append(".").append(method).append(" exception: ");
LogUtil.logException(buffer.toString(), ex);
ModelAndView mv = new ModelAndView();
FastJsonJsonView view = new FastJsonJsonView();
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("status", CommonConstant.EXCEPTION_CODE_500);
attributes.put("message", CommonConstant.MSG_FAIL);
view.setAttributesMap(attributes);
mv.setView(view);
return mv;
}

/**
* 业务处理BizException
* @param ex
* @param req
* @return
*/
@ExceptionHandler(value = {BizException.class})
public ModelAndView resolveBizException(HttpServletRequest request,BizException ex) {
ModelAndView mv = new ModelAndView();
FastJsonJsonView view = new FastJsonJsonView();
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("status", ex.getCode());
attributes.put("message", ex.getMsg());
view.setAttributesMap(attributes);
mv.setView(view);
return mv;
}
}

BizException定义:

package cc.messcat.common.exception;
/**
*
* ClassName: BizException
* @Description: 业务异常基类,所有业务异常都必须继承于此异常
* @author limh
* @date 2017年3月11日
*/
public class BizException extends RuntimeException {
private static final long serialVersionUID = -5875371379845226068L;
/**
* 数据库操作,insert返回0
*/
public static final BizException DB_INSERT_RESULT_0 = new BizException(
20010001, "数据库操作,insert返回0");
/**
* 数据库操作,update返回0
*/
public static final BizException DB_UPDATE_RESULT_0 = new BizException(
20010002, "数据库操作,update返回0");
/**
* 数据库操作,selectOne返回null
*/
public static final BizException DB_SELECTONE_IS_NULL = new BizException(
20010003, "数据库操作,selectOne返回null");
/**
* 数据库操作,list返回null
*/
public static final BizException DB_LIST_IS_NULL = new BizException(
20010004, "数据库操作,list返回null");
/**
* Token 验证不通过
*/
public static final BizException TOKEN_IS_ILLICIT = new BizException(
20010005, "Token 验证非法");
/**
* 会话超时 获取session时,如果是空,throws 下面这个异常 拦截器会拦截爆会话超时页面
*/
public static final BizException SESSION_IS_OUT_TIME = new BizException(
20010006, "会话超时");
/**
* 异常信息
*/
protected String msg;
/**
* 具体异常码
*/
protected int code;
public BizException(int code, String msgFormat, Object... args) {
super(String.format(msgFormat, args));
this.code = code;
this.msg = String.format(msgFormat, args);
}
public BizException() {
super();
}
public String getMsg() {
return msg;
}
public int getCode() {
return code;
}
/**
* 实例化异常
*
* @param msgFormat
* @param args
* @return
*/
public BizException newInstance(String msgFormat, Object... args) {
return new BizException(this.code, msgFormat, args);
}
public BizException(String message, Throwable cause) {
super(message, cause);
}
public BizException(Throwable cause) {
super(cause);
}
public BizException(String message) {
super(message);
}
}
BaseException定义:

/**
* Description: <br/>
*/
package cc.messcat.common.exception;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* ClassName: BaseException
* @Description: TODO
* @author limh
* @date 2017年3月11日
*/
public class BaseException extends BizException {
private static final long serialVersionUID = 662981704729484572L;
private static final Log log = LogFactory.getLog(BaseException.class);
/**
* 异常code
*/
public final static int TICKET_NOTE_TYPE_IS_NOT_AVAILABLE = 21040031;

public BaseException() {
}
public BaseException(int code, String msgFormat, Object... args) {
super(code, msgFormat, args);
}
public BaseException(int code, String msg) {
super(code, msg);
}
/**
* 实例化异常
*
* @param msgFormat
* @param args
* @return
*/
public BaseException newInstance(String msgFormat, Object... args) {
return new BaseException(this.code, msgFormat, args);
}
public BaseException print() {
log.info("==>BizException, code:" + this.code + ", msg:" + this.msg);
return new BaseException(this.code, this.msg);
}
}
调用例子:

Route route = routeTravelAppService.getRouteInfo(routeId);
if(route == null ){
throw new BaseException(BaseException.TICKET_NOTE_TYPE_IS_NOT_AVAILABLE,"行程为空");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SpirngMvc异常处理