1.使用 SimpleMappingExceptionResolver 实现异常处理
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!-- 异常处理页面 --> <property name="defaultErrorView" value="error"></property> <!-- 异常信息的变量名,默认名为exception --> <property name="exceptionAttribute" value="ex"></property> <!-- 需要处理的异常 --> <property name="exceptionMappings"> <props> <prop key="xxxxException">error-xxx</prop> <prop key="yyyyException">error-yyy</prop> <prop key="...">...</prop> </props> </property> </bean>
2.实现HandlerExceptionResolver 接口自定义异常处理器
public class DefaultExceptionHandler implements HandlerExceptionResolver { @Override public ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object o, Exception e) { return new ModelAndView("error"); } }
3.使用@ControllerAdvice,@ExceptionHandler 注解实现
@ControllerAdvice public class DefaultExceptionHandler { @ExceptionHandler(Throwable.class) public ModelAndView resolveException(Exception ex) { // FastJsonJsonView HashMap<String, Object> map = new HashMap<>(); map.put("code", "1001"); map.put("msg", ex.getMessage()); log.error("异常:" + ex.getMessage(), ex); return new ModelAndView("error", map); } }