SpringMVC异常处理 自定义异常

异常处理器

实现HandlerExceptionResolver接口(异常处理器)


@Component // 配上注解Spring看到实现了这个接口就知道是异常处理器了
public class ExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {
        System.out.println("异常处理器正在执行中");
        ModelAndView modelAndView = new ModelAndView();
        //定义异常现象出现后,反馈给用户查看的信息
        modelAndView.addObject("msg","出错啦! ");
        //定义异常现象出现后,反馈给用户查看的页面
        modelAndView.setViewName("error.jsp");
        return modelAndView;
    }
}

根据异常的种类不同,进行分门别类的管理,返回不同的信息

public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {
        System.out.println("my exception is running ...."+ex);
        ModelAndView modelAndView = new ModelAndView();
        
        if( ex instanceof NullPointerException){
            modelAndView.addObject("msg","空指针异常");
        }else if ( ex instanceof  ArithmeticException){
            modelAndView.addObject("msg","算数运算异常");
        }else{
            modelAndView.addObject("msg","未知的异常");
        }
        
        modelAndView.setViewName("error.jsp");
        return modelAndView;
    }
}
注解开发异常处理器:

使用注解实现异常分类管理

  • 名称: @ControllerAdvice
  • 类型: 类注解
  • 位置:异常处理器类上方
  • 作用:设置当前类为异常处理器类
@Component
@ControllerAdvice
public class ExceptionAdvice {
}  

使用注解实现异常分类管理

  • 名称: @ExceptionHandler
  • 类型: 方法注解
  • 位置:异常处理器类中针对指定异常进行处理的方法上方
  • 说明:处理器方法可以设定多个
@Component // 异常类只能有一个,多个的情况会都执行,会报错
@ControllerAdvice
public class ExceptionAdvice {

// 可以根据不同的异常  写多个异常方法
	@ExceptionHandler(NullPointerException.class)// 调用异常名
	@ResponseBody // 只让结果返回的是字符串类型的,否则会直接去匹配页面
		public String doOtherException(Exception ex){ // 写上参数可以拿到具体的参数
   			return "出错啦,请联系管理员! ";
	} 
}  
异常分类:

工作中肯定是不能直接去定义一个异常类,然后挨个匹配异常,可能不同的异常给用户展示 写到死。

业务异常:

  • 发送对应消息传递给用户,提醒规范操作

系统异常:

  • 发送固定消息传递给用户,安抚用户
  • 发送特定消息给运维人员,提醒维护
  • 记录日志

其他异常:

  • 发送固定消息传递给用户,安抚用户
  • 发送特定消息给编程人员,提醒维护
  • 纳入预期范围内
  • 记录日志
自定义异常

用户行为异常类

//自定义异常继承RuntimeException,覆盖父类所有的构造方法
public class BusinessException extends RuntimeException {
    public BusinessException() {
    }

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(String message, Throwable cause) {
        super(message, cause);
    }

    public BusinessException(Throwable cause) {
        super(cause);
    }

    public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

系统异常:

//自定义异常继承RuntimeException,覆盖父类所有的构造方法
public class SystemException extends RuntimeException {
    public SystemException() {
    }

    public SystemException(String message) {
        super(message);
    }

    public SystemException(String message, Throwable cause) {
        super(message, cause);
    }

    public SystemException(Throwable cause) {
        super(cause);
    }

    public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

自定义异常触发类

@Controller
public class UserController {
    @RequestMapping("/save")
    @ResponseBody
    public List<User> save(@RequestBody User user) {
        System.out.println("user controller save is running ...");

        //模拟业务层发起调用产生了异常
//        int i = 1/0;
//        String str = null;
//        str.length();

        //对用户的非法操作进行判定,并包装成异常对象进行处理,便于统一管理
        if(user.getName().trim().length() < 8){
            throw new BusinessException("对不起,用户名长度不满足要求,请重新输入!");
        }
        if(user.getAge() < 0){
            throw new BusinessException("对不起,年龄必须是0到100之间的数字!");
        }
        if(user.getAge() > 100){
            throw  new SystemException("服务器连接失败,请尽快检查处理!");
        }


        User u1 = new User();
        u1.setName("Tom");
        u1.setAge(3);
        User u2 = new User();
        u2.setName("Jerry");
        u2.setAge(5);
        ArrayList<User> al = new ArrayList<User>();
        al.add(u1);
        al.add(u2);

        return al;
    }
}

Ajax处理

<%@page pageEncoding="UTF-8" language="java" contentType="text/html;UTF-8" %>

<a href="javascript:void(0);" id="testException">访问springmvc后台controller,传递Json格式POJO</a><br/>

<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>

<script type="text/javascript">
    $(function () {
        $("#testException").click(function(){
            $.ajax({
                contentType:"application/json",
                type:"POST",
                url:"save",
                /*通过修改参数,激活自定义异常的出现*/
                // name长度低于8位出现业务异常
                // age小于0出现业务异常
                // age大于100出现系统异常
                // age类型如果无法匹配将转入其他类别异常
                data:'{"name":"Jock","age":"111"}',
                dataType:"text",
                //回调函数
                success:function(data){
                    alert(data);
                }
            });
        });
    });
</script>

通过自定义异常将所有的异常现象进行分类管理,以统一的格式对外呈现异常消息,部分异常是面向用户,部分是面向内部的,比如说服务器出现了故障,告诉用户出错了就行了,不需要显示具体的原因,然后发送异常给内部人员进行处理操作

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring MVC中,可以通过实现HandlerExceptionResolver接口来进行自定义异常处理。这个接口定义了一个resolveException()方法,当请求处理过程中出现异常时会被调用。通过实现这个方法,我们可以自定义异常处理的逻辑。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springmvc自定义异常处理](https://blog.csdn.net/Sunking_Yin/article/details/52744151)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [SpringMVC自定义异常处理](https://blog.csdn.net/A_jungle/article/details/82386793)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [ssm_异常处理](https://download.csdn.net/download/csdn_kenneth/10251825)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itzhuzhu.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值