关闭

springmvc 统一异常处理 实现 HandlerExceptionResolver接口

79人阅读 评论(0) 收藏 举报

1,sping配置文件中添加

<!-- 异常拦截 -->
<bean id="exceptionResolver" class="com.htys.interceptor.Exceptionhandler"/>  

2,实现HandlerExceptionResolver接口

@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
if(ex!=null){
ex.printStackTrace();
}
String o=null;
try {
o=((HandlerMethod)handler).getMethod().getReturnType().getSimpleName();
} catch (Exception e) {
}
if (o != null) {
if (o.equals(JSONResult1.class.getSimpleName())) {
response.setContentType("text/html;charset=UTF-8");
// 设置状态码
PrintWriter w = null;
try {
w = response.getWriter();
String ss = Util.getLaseCause(ex);
ss=(ss == null||"null".equals(ss)) ? "空指针" : ss;
if(ss.equals("成功")){
response.setStatus(200);
w.write(JSON.toJSONString(new JSONResult1("成功", true)));
}else{
response.setStatus(1000);
w.write(ss);
}
ss = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
w.flush();
w.close();
}
return new ModelAndView();
} else if (o.equals(JSONResult.class.getSimpleName())) {
response.setContentType("text/html;charset=UTF-8");
// 设置状态码
response.setStatus(1000);
PrintWriter w = null;
try {
w = response.getWriter();
String ss = Util.getLaseCause(ex);
w.write((ss == null||"null".equals(ss)) ? "空指针" : ss);
ss = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
w.flush();
w.close();
}
return new ModelAndView();
} else if(o.equals(PCJson.class.getSimpleName())){
response.setContentType("text/html;charset=UTF-8");
// 设置状态码
response.setStatus(1000);
PrintWriter w = null;
try {
w = response.getWriter();
String ss = Util.getLaseCause(ex);
w.write((ss == null||"null".equals(ss)) ? "空指针" : ss);
ss = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
w.flush();
w.close();
}
return new ModelAndView();
}
}
ModelAndView mv=new ModelAndView("error");
String ss = Util.getLaseCause(ex);//获取根异常
mv.addObject("error", (ss == null||"null".equals(ss)) ? "空指针" : ss);
return mv;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:79次
    • 积分:10
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档