spring项目全局异常处理

首先描述实现的功能:因为在项目中,我们不可否认的会出现异常,而且这些异常并没有进行捕获。经常出现的bug如空指针异常等等。

在之前的项目中,如果我们没有进行任何配置,那么容器会自动打印错误的信息,如果tomcat的404页面,400页面等等。

如果我们在web.xml中进行如下配置,就会拦截错误,然后跳转到指定的错误页面。

<error-page>
    <error-code>500</error-code>
    <location>/500.jsp</location>
</error-page>

但是这已经落后了,现在我们通过实现spring的HandlerExceptionResolver接口来捕获所有的异常。

public class CustomExceptionResolver implements HandlerExceptionResolver {
    private static Logger logger = LoggerFactory.getLogger(CustomExceptionResolver.class);
    //wise自定义错误 throw 后需要截取exception.message中有效的json信息
    private static final int SUBSTRLENG="com.hanshow.wise.common.exception.WiseException: ".length();
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        ModelAndView modelAndView = new ModelAndView();
        response.setStatus(HttpStatus.OK.value()); //设置状态码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            if (exception instanceof LoginValidateException) {
                LoginValidateException loginValidateException = (LoginValidateException) exception;
                response.getWriter().write(loginValidateException.getMessage());
                logger.error("The-global-exception-handler-class-catches-exceptions-securityKey:" ,exception);
            } else if (exception instanceof WiseException) {
                WiseException wiseException = (WiseException) exception;
                response.getWriter().write(wiseException.getMessage());
                logger.error("The-global-exception-handler-class-catches-exceptions-hand:" , exception);
            } else if (exception.getMessage().contains("WiseException:")) { //中台自定义错误异常
                String exceptionMessages[] = exception.getMessage().split("\n");
                if (exceptionMessages.length >= 2) {
                    if (exceptionMessages[0].length() >= SUBSTRLENG) {
                        String wiseExceptionMes = exceptionMessages[0].substring(SUBSTRLENG);
                        logger.info("WiseException={}", StringUtil.formatJson(JSONObject.fromObject(wiseExceptionMes).toString()));
                        response.getWriter().write(wiseExceptionMes);
                    }
                }
                logger.error("The-global-exception-handler-class-catches-exceptions-WiseException:", exception);
            } else {
                BaseDTO objectBaseDTO = BaseDTO.genErrBaseDTO(BaseError.INNER_DATA_ERROR);
                Map<String, Object> returnMap = new HashMap<>();
                returnMap.put("errMsg", exception.getMessage());
                returnMap.put("exception", exception);
                objectBaseDTO.setData(returnMap);
                if (objectBaseDTO.getRequestId() == null) {
                    objectBaseDTO.setRequestId(UUIDUtils.genUUID());
                }
                response.getWriter().write(JSONObject.fromObject(objectBaseDTO).toString());
                logger.error("The-global-exception-handler-class-catches-exceptions-runexception-mes:" , exception);
            }

        } catch (Exception e) {
            logger.error("全局异常处理失败", e);
        }
        return modelAndView;
    }
}

在spring配置文件中配置刚才新建的类

<bean id="exceptionResolver" class="com.hanshow.wise.portal.eshop.resolver.CustomExceptionResolver"></bean>

在你在开发的时候,请返回null,这样这个类就如同不起作用,之前该怎么样就怎么样。

当开发完成之后,根据错误的信息来返回需要的东西了。

首先我们可以做的是打印错误日志,当然也是必须的。

System.err.println(“访问” + request.getRequestURI() + " 发生错误, 错误信息:" + exception.getMessage());

这里我只是用控制台举例,你当然可以用日志框架打印。打印信息主要是包括是访问那个地址出现了什么错误。

之后如果你需要返回错误页面,那么就直接在ModelAndView里面写就行了,这里就不多举例了,ModelAndView写过MVC的Controller应该都熟悉。

ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
return modelAndView;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值