springmvc中自定義異常處理器輸出異常信息



1.可以使用springmvc提供的HandlerExceptionResolver,來實現統一的異常處理。

package com.catchu.utils;import com.alibaba.fastjson.JSON;import org.apache.shiro.authz.AuthorizationException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.dao.DuplicateKeyException;import org.springframework.stereotype.Component;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 異常處理器 * @author 劉俊重 * @email magichair522@gmail.com */@Componentpublic class MagicExceptionHandler implements HandlerExceptionResolver {private Logger logger = LoggerFactory.getLogger(getClass());@Overridepublic ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {WebResult result = new WebResult();try {response.setContentType("application/json;charset=utf-8");response.setCharacterEncoding("utf-8");if (ex instanceof CatchUException) {result.put("code", ((MagicException) ex).getCode());result.put("msg", ((MagicException) ex).getMessage());}else{result = Out.error();}//記錄異常日志logger.error(ex.getMessage(), ex);String json = JSON.toJSONString(result);response.getWriter().print(json);} catch (Exception e) {logger.error("CatchUExceptionHandler 異常處理失敗", e);}return new ModelAndView();}}

2.MagicException異常類定義如下:

package com.magic.lang;
/**
* @author 劉俊重
* @Description 自定義異常
*/
public class MagicException extends RuntimeException {

private String msg;

private int code;

public MagicException(String msg){
super(msg);
this.msg = msg;
}

public MagicException(String msg,Throwable e){
super(msg,e);
this.msg = msg;
}

public MagicException(String msg,int code){
super(msg);
this.msg = msg;
this.code = code;
}

public MagicException(String msg,int code,Throwable e){
super(msg,e);
this.msg = msg;
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}
}



                           

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: