SpringMVC之配置异常处理器

 

1.模拟异常访问

@Controller
@RequestMapping("/test")
public class ExceptionTest {
    @RequestMapping("/1")
    public String test1() throws SysException{
        try {
            System.out.println(1/0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SysException("除数为零");
        }
        return "success";
    }
}

 

2.自定义异常类

public class SysException extends Exception{
    private String message;

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

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

}

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

public class SysExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof SysException){
            e = (SysException) e;
        }else {
            e = new SysException("该项功能正在维护中...");
        }
        ModelAndView view = new ModelAndView();
        view.addObject("errorMsg",e.getMessage());
        view.setViewName("error");
        return view;
    }
}

4.在spring配置文件中添加异常处理器的bean


    
    
        
        
    
    
    

 

 

你可能感兴趣的:(SpringMVC)