ssm 全局异常处理

最近看了一个比较不错的视屏分享给大家https://www.bilibili.com/video/av20669583/?p=6很适合我们新手学习。

在ssm项目中, 用户访问控制层,再到服务层,再到DAO层, 每一层都有可能出现异常。可以把每层的异常往上抛,抛给最外面的控制层,然后将这个错误显示到一个error.jsp页面上来提示用户网页出错了, 这样就比较人性化。 有时候控制层的方法是想返回json数据,并不想转到error.jsp界面上, 这种情况也可以在被处理。

步骤

建个exception包,存放异常处理类
这里写图片描述

CustomException类, 其中message存放异常消息

public class CustomException extends Exception{

    public String message;

    public CustomException(String message){
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

CustomExceptionResolver 类, 判断是带有@ResponseBody 。


public class CustomExceptionResolver implements HandlerExceptionResolver {


    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         Object o,
                                         Exception e) {

        CustomException customException = null;

        if (e instanceof CustomException){ //此错误是我们预期的错误
            customException = (CustomException)e;

        }else{ //非预期错误
            customException = new CustomException("未知错误");
        }
        String message = customException.getMessage(); //错误文字信息
        ModelAndView modelAndView = new ModelAndView();

        //判断请求的类型, 是否是json
        HandlerMethod handlerMethod = (HandlerMethod) o;
        ResponseBody responseBody = handlerMethod.getMethod().getAnnotation(ResponseBody.class);
        //是json请求, 则放回json数据
        if (responseBody != null){
            //设置状态码和信息
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("code", "0");
            responseMap.put("message", message);
            String json = new Gson().toJson(responseMap);
            System.out.println(json);
            httpServletResponse.setContentType("UTF-8");
            httpServletResponse.setContentType("application/json;charset=utf-8");
            try{
                httpServletResponse.getWriter().write(json);
                httpServletResponse.getWriter().flush();;
            }catch (IOException e1){
                e1.printStackTrace();
            }
            return modelAndView;
        }

        modelAndView.addObject("message", message);

        //不是json数据, 携带message到跳转到错误页面
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

控制层方法部分代码, 当用户名密码为空时, 抛出异常消息

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new CustomException("用户名或密码不能为空");
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值