springMVC的统一异常处理

xiaoxiao2021-02-27  152

一. 异常的种类

运行时异常(RuntimeException)编译异常(程序员写的代码可能出错的地方), 处理: - throws抛到最后进行处理 - try…catch

二. springMVC的统一异常处理

springMVC的自带异常处理器: HandlerExceptionResolver

缺点:

将原生的异常信息响应给了用户;用户体验差;

三. 解决思路

将原生异常信息转成用户能看懂的信息 — 需要自定义异常;自定义异常后, springMVC的自带异常处理器HandlerExceptionResolver并不认识这个自定义异常, 我们还需要自定义一个异常处理器(实现HandlerExceptionResolver接口), 处理我们自己的异常信息. 代码中抛出所有异常.

四. 异常处理的实现

1.首先自定义异常:

public class CustomException extends Exception{ private String msg; public CustomException(String msg){ this.msg = msg; } public void setMsg(String msg){ this.msg = msg; } public String getMsg(){ return msg; } }

2.自定义异常处理器(实现HandlerExceptionResolver)

public class CustomExceptionResolver implements HandlerExceptionResolver{ @Override public ModelAndView resolverException(HttpServletRequest request, HttpServletResponse response, Exception exception){ // 判断抛出的异常是否是自定义异常 CustomException customException; if(exception instanceof CustomException){ // 是 customException = (CustomException) exception; }else{ // 系统异常 customException = new CustomException("未知错误!"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error"); modelAndView.addObject("error",customException.getMsg()); return modelAndView; } }

3.加载自定义的异常处理器 — springMVC.xml

<!-- 加载自定义异常处理器 --> <bean class="online.bendou.exception.CustomExceptionResolver" />

4.添加error页面 在error.jsp中取出错误信息: ${error}

5.处理代码中可能出错的地方

public User queryUser(Integer id) throws CustomException{ User user = userMapper.findById(id); if(user != null){ return user; }else{ throw new CustomException("用户不存在!"); } }

异常抛到最后, 将被异常处理器处理.

转载请注明原文地址: https://www.6miu.com/read-16404.html

最新回复(0)