博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMVC框架四:异常处理器
阅读量:4674 次
发布时间:2019-06-09

本文共 2520 字,大约阅读时间需要 8 分钟。

.异常分为:预期异常、运行时异常

dao、service、controller三层中有异常,依次向上抛出直到SpringMVC处理。

而SpringMVC交给HandlerExceptionResolver(异常处理器)

程序员则需要实现这个类

 

示例:

package org.dreamtech.springmvc.exception;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;/** *  * @author YiQing *  *         异常处理器自定义实现类 */public class CustomExceptionResolver implements HandlerExceptionResolver {    @Override    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,            Exception e) {        /*         * request 请求 response 响应          * obj 字符串,发生异常的地方(包名.类名.方法名)         * e 异常         */                ModelAndView mav = new ModelAndView();        mav.addObject("error","异常");        mav.setViewName("error");                return mav;    }}

 

使用前记得配给SpringMVC:

 

 

 

解释:如果程序中出现了异常,就会执行这个方法,并且返回error视图

使用场景:开发网站时候,用户由于不当操作使程序异常,会看到Tomcat报错,这大大影响用户体验,可以统一设置一个错误页面,友好提示

 

 

上边这种方式异常不在意料之中,而如果我们需要主动抛出异常的话(预期异常):

使用场景:用户注册时候,用户名密码不能为空(如果不采取前端校验),这时候可以在后端主动抛出异常,并返回对应提示信息

 

首先自定义异常:

package org.dreamtech.springmvc.exception;/** * 自定义异常 * @author YiQing * */public class MessageException extends Exception {    private String msg;    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public MessageException(String msg) {        super();        this.msg = msg;    }}

 

主动触发异常:

if(username==""){            throw new MessageException("用户名不为空");        }

 

 

这时候异常处理器就可以修改成完整版:

package org.dreamtech.springmvc.exception;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;/** *  * @author YiQing *  */public class CustomExceptionResolver implements HandlerExceptionResolver {    @Override    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,            Exception e) {        ModelAndView mav = new ModelAndView();        if (e instanceof MessageException) {            MessageException me = (MessageException) e;            mav.addObject("error", me.getMsg());            mav.setViewName("login");        } else {            mav.addObject("error", "未知异常");            mav.setViewName("error");        }        return mav;    }}

 

转载于:https://www.cnblogs.com/xuyiqing/p/9429525.html

你可能感兴趣的文章