全局异常处理总结

自定义异常及异常全局处理:
https://blog.csdn.net/qidasheng2012/article/details/84550539

全局异常处理实例
https://blog.csdn.net/qidasheng2012/article/details/84548833

1、WEB.XML
就是指定error-code和page到指定地址,这也是最传统和常见的做法
web.xml:

 <error-page>
     <error-code>404</error-code>
     <location>/404</location>
 </error-page>
 <error-page>
     <error-code>500</error-code>
     <location>/500</location>
 </error-page>

 <!-- 未捕获的错误,同样可指定其它异常类,或自定义异常类 -->
 <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/uncaughtException</location>
 </error-page>

applicationContext.xml:

<!-- 错误路径和错误页面,注意指定viewResolver -->
<mvc:view-controller path="/404" view-name="404"/>
<mvc:view-controller path="/500" view-name="500"/>
<mvc:view-controller path="/uncaughtException" view-name="uncaughtException"/>

2、Spring全局异常,Controller增强方式( Advising Controllers)
异常抛出:

@Controller
public class MainController {
    @ResponseBody
    @RequestMapping("/")
    public String testException(){
        throw new NullPointerException("NullPointerException Test!");
    }
}

异常捕获:

//注意使用注解@ControllerAdvice作用域是全局Controller范围,即必须与抛出异常的method在同一个controller
//可应用到所有@RequestMapping类或方法上的@ExceptionHandler、@InitBinder、@ModelAttribute,在这里是@ExceptionHandler

@ControllerAdvice
public class AControllerAdvice {
   
   @ExceptionHandler(NullPointerException.class)
   @ResponseStatus(HttpStatus.BAD_REQUEST)
   @ResponseBody
   public String handleIOException(NullPointerException ex) {
       return ClassUtils.getShortName(ex.getClass()) + ex.getMessage();
   }
   
}

为了确保@ResponseStatus标注的异常被Spring框架处理,可以这样编写全局异常处理类:

@ControllerAdvice
class GlobalDefaultExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;

        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
}

3、Spirng全局异常,配置方式

异常抛出,同上!

异常捕获:

<!-- 全局异常配置 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
 <property name="exceptionMappings">
     <props>
         <prop key="java.lang.Exception">errors/500</prop>
         <prop key="java.lang.Throwable">errors/500</prop>
     </props>
 </property>
 
 <property name="statusCodes">
      <props>
          <prop key="errors/500">500</prop>
      </props>
  </property>
  
  <!-- 设置日志输出级别,不定义则默认不输出警告等错误日志信息 -->
  <property name="warnLogCategory" value="WARN"></property>
  
  <!-- 默认错误页面,当找不到上面mappings中指定的异常对应视图时,使用本默认配置 -->
  <property name="defaultErrorView" value="errors/500"></property>
  
  <!-- 默认HTTP状态码 -->
  <property name="defaultStatusCode" value="500"></property>
  
</bean>

对应500错误的view jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>500 Error</title>
    </head>
    <body>
        <% Exception ex = (Exception)request.getAttribute("exception"); %>
        <H2>Exception:<%= ex.getMessage()%></H2>
        <P/>
        <% ex.printStackTrace(new java.io.PrintWriter(out)); %>
    </body>
</html>

4、Sping全局异常,自定义异常类和异常解析
自定义异常类:

public class CustomException extends RuntimeException {

   public CustomException(){
       super();
   }

   public CustomException(String msg, Throwable cause){
       super(msg, cause);
       //Do something...
    }
}

抛出异常:

@ResponseBody
@RequestMapping("/ce")
public String ce(CustomException e){
    throw new CustomException("msg",e);
}

实现异常捕获接口HandlerExceptionResolver:

public class CustomHandlerExceptionResolver implements HandlerExceptionResolver{

   @Override
   public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
       Map<String, Object> model = new HashMap<String, Object>();
       model.put("e", e);
       //这里可根据不同异常引起类做不同处理方式,本例做不同返回页面。
       String viewName = ClassUtils.getShortName(e.getClass());
       return new ModelAndView(viewName, model);
    }
    
}

新的的HandlerExceptionResolver实现类只需在配置文件中定义即可,可以配置优先级。DispatcherServlet初始化HandlerExceptionResolver的时候会自动寻找容器中实现了HandlerExceptionResolver接口的类,然后添加进来。配置Spring支持异常捕获:

<bean class="cn.bg.controller.CustomHandlerExceptionResolver"/>

5、Errors and REST
使用Restful的Controller可以使用@ResponseBody处理错误,首先定义一个错误:

public class ErrorInfo {
    public final String url;
    public final String ex;
    
    public ErrorInfo(String url, Exception ex) {
        this.url = url;
        this.ex = ex.getLocalizedMessage();
    }
}

通过一个@ResponseBody返回一个错误实例:

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MyBadDataException.class)
@ResponseBody ErrorInfo handleBadRequest(HttpServletRequest req, Exception ex) {
    return new ErrorInfo(req.getRequestURL(), ex);
} 

转自:https://blog.csdn.net/u011877584/article/details/78853816

猜你喜欢

转载自blog.csdn.net/qidasheng2012/article/details/84544856
今日推荐