SpringMvc中的统一异常处理器

xiaoxiao2021-02-28  7

一般项目中都需要作异常处理,基于系统架构的设计考虑,使用统一的异常处理方法,这些异常有可能是预期的可能发生的,这个时候我们可以捕获它,但是也有一些异常是运行时才会发生的,我们无从捕获它,此时也需要统一的异常处理

在SpringMVC中我们需要可以自定义一个(一般为多个)异常类,遇到可以预期的异常是的时候,捕获相应的自定义的异常,遇到运行时产生的异常的时候,在统一的异常处理器中捕获,实现统一的异常处理,需要实现一个接口HandlerExceptionResolver,并在spring容器中注册

public class CustomerException extends Exception { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public CustomerException(String message) { super(); this.message = message; } } public class CustomerExceptionResolver implements HandlerExceptionResolver{ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = new ModelAndView(); ex.printStackTrace(); CustomerException customerException = null; if(ex instanceof CustomerException){ customerException = (CustomerException)ex; }else{ customerException = new CustomerException("未知的错误"); } String message = customerException.getMessage(); request.setAttribute("message", message); try { request.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return modelAndView; } } <!-- 配置异常处理器 --> <bean class="com.njust.ssm.exception.resolver.CustomerExceptionResolver"></bean>
转载请注明原文地址: https://www.6miu.com/read-850316.html

最新回复(0)