spring自定义异常处理

项目运行过程中出现错误后,希望页面跳转到一个通用的错误页面。 spring提供了一个接口HandlerExceptionResolver,自己实现这个接口即可。

java代码如下:

package com.wx.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.wx.redpacket.controller.ResponseResult;
import com.wx.utils.Utils;

/**
 * 通用异常处理
 * 
 * @author
 * @version
 */

@Component
public class CustomExceptionHandler implements HandlerExceptionResolver {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 
     * 处理异常方法
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception exception) {

        // 权限问题抛出的异常,返回登录页面
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            // 如果不是异步请求

            String resultSmg = "";

            // TargetNotFound异常统一处理
            if (exception instanceof TargetNotFoundException) {
                TargetNotFoundException exp = (TargetNotFoundException) exception;
                String message = exp.getMessage();
                resultSmg = "很抱歉," + (StringUtils.isNotBlank(message) ? message : "");
            } else if (exception instanceof RequestParameterException) {
                // 参数错误
                RequestParameterException exp = (RequestParameterException) exception;
                String paramName = exp.getParamName();
                String validMsg = exp.getValidMsg();
                resultSmg = paramName + "参数值错误,请修正后提交!"
                        + (StringUtils.isNotBlank(validMsg) ? ("[修正参考: " + validMsg + "]") : "");
            } else if (exception instanceof ServiceException) {
                // 业务异常
                ServiceException exp = (ServiceException) exception;
                resultSmg = exp.getMessage();
            } else {
                // 未知异常
                resultSmg = "很抱歉,系统发生未知错误!如需要帮助请联系管理员为您解决!";
            }

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("errorMsg", resultSmg);
            map.put("exception", Utils.getStackTrace(exception));

            logger.warn("ui exception:" + exception.getMessage(), exception);
            return new ModelAndView("exception", map);    //返回到exception页面

        } else if ("POST".equalsIgnoreCase(request.getMethod())) {// JSON格式返回
            ResponseResult resp = new ResponseResult(false);

            // TargetNotFound异常统一处理
            if (exception instanceof TargetNotFoundException) {
                TargetNotFoundException exp = (TargetNotFoundException) exception;
                String message = exp.getMessage();
                resp.setResultSmg("很抱歉," + (StringUtils.isNotBlank(message) ? message : ""));
            } else if (exception instanceof RequestParameterException) {
                RequestParameterException exp = (RequestParameterException) exception;
                String paramName = exp.getParamName();
                String validMsg = exp.getValidMsg();
                resp.setResultSmg(paramName + "参数值错误,请修正后提交!"
                        + (StringUtils.isNotBlank(validMsg) ? ("[修正参考: " + validMsg + "]") : ""));
            } else if (exception instanceof ServiceException) {
                ServiceException exp = (ServiceException) exception;
                resp.setResultSmg(exp.getMessage());
            }  else {
                resp.setResultSmg("很抱歉,系统发生未知错误!如需要帮助请联系管理员为您解决!");
            }

            try {
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                JSONObject json = JSONObject.fromObject(resp);
                writer.write(json.toString());
                writer.flush();
            } catch (IOException e) {
                logger.error("Error Occurred in Globle Exception Handler!", e);
            }
            return null;
        }
        return null;
    }
}



exception.jsp如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui">
</head>

<body>
<div id="main">
	<div id="container">
		<div class="content">
			<h4 class="menu_path">系统错误:系统出现错误,请联系系统管理员报告此错误!</h4>
			<div>错误信息:${errorMsg}</div>
		</div>
	</div>
</div>
</body>
</html>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值